从抛出的自定义异常中获取自定义消息

Get custom message out of the custom exception thrown

我正在为我的一个资源post 方法编写测试

@POST
@Path("/api")
@Timed
@UnitOfWork
@Consumes(MediaType.APPLICATION_JSON)

public Person createPerson(Person p, @Context UriInfo uriInfo) {
      //do something here or throw 400 exception

}

这是测试

@Test
public void testThrows400() throws Exception {

thrown.expect(400Exception.class);
Response response = resources.client().target("/api").request(MediaType.APPLICATION_JSON).post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE));
assertEquals(response.getStatus(), 400);
assertEquals(response.getStatusInfo(), Status.BAD_REQUEST);

}

这是按预期工作的。但是有什么方法可以 return 抛出异常时发送的自定义消息?

这里是例外class

public class InvalidNameException  extends WebApplicationException
{
    private static final long serialVersionUID = 1L;


    public InvalidNameException(URI location)
    {
        this(location, null);
    }
    public InvalidNameException(URI location, Object entity) {
         super(Response.status(Status.BAD_REQUEST).location(location).entity("Invalid name, please use a valid name").build());
    }


}

您可以使用类似的代码块,发送的响应将具有 HTTP 状态 400 以及您的自定义消息。

首先,添加一个将您的消息作为输入的构造函数。

public InvalidNameException(String message) {
    super(message);
}

if (invalidName) throw new InvalidNameException("My custom message goes here");

除此之外,使用 ExceptionMapper。

public class InvalidNameMapper implements ExceptionMapper<InvalidNameException> {
    @Override
    public Response toResponse(InvalidNameException e) {
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
    }
}

您需要向框架注册您的 InvalidNameMapper。 对于 Dropwizard,您可以在应用程序 class.

的 运行() 方法中按如下方式执行此操作
environment.jersey().register(InvalidNameMapper.class);