是否可以在 BadRequestException
中包含一条消息所以当用户看到响应代码 a 400 时,他/她也能找出原因?
场景将是这样的,经过简化:
public Entity getEntityWithOptions(@PathParam("id") String id, @QueryParam("option") String optValue) {
if (optValue != null) {
// Option is an enum
try {
Option option = Option.valueOf(optValue);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
return new Entity(option);
}
return new Entity();
}
我知道这可以通过返回 Response
来完成反对,但我不想那样。
这可能吗?也许用 ExceptionMapper<BadRequestException>
?或者这无法完成,因为 BadRequestException
已经是 Jersey 特有的异常?
最佳答案
有一个非常简单的方法,如下所示。
Response.ResponseBuilder resp_builder=Response.status(Response.Status.BAD_REQUEST);
resp_builder.entity(e.getMessage());//message you need as the body
throw new WebApplicationException(resp_builder.build());
如果您需要添加 header 、响应媒体类型或其他一些功能,ResponseBuilder 提供了所有这些。
关于java - 如何在 BadRequestException 中包含消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38104420/