Java 如何在BadRequestException中包含消息?
是否可以在Java 如何在BadRequestException中包含消息?,java,web-services,http,jersey,jax-rs,Java,Web Services,Http,Jersey,Jax Rs,是否可以在BadRequestException中包含一条消息,以便用户在看到响应代码a 400时,也能找出原因 场景类似于这样,简化了: public Entity getEntityWithOptions(@PathParam("id") String id, @QueryParam("option") String optValue) { if (optValue != null) { // Option is an enum try {
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();
}
我知道这可以通过返回响应
对象来实现,但我不希望这样
这可能吗?可能带有一个
例外标记?或者,由于BadRequestException
已经是一个特定于Jersey的异常,因此无法执行此操作。您应该创建这样一个自定义异常
public class CustomBadReq extends WebApplicationException {
public CustomBadReq(String message) {
super(Response.status(Response.Status.BAD_REQUEST)
.entity(message).type(MediaType.TEXT_PLAIN).build());
}
}
另请参见您可以抛出CustomException并将其映射到CustomExceptionMapper以提供自定义响应
public class CustomException extends RuntimeException {
public CustomException(Throwable throwable) {
super(throwable);
}
public CustomException(String string, Throwable throwable) {
super(string, throwable);
}
public CustomException(String string) {
super(string);
}
public CustomException() {
super();
}
}
@Provider
public class CustomExceptionMapper implements ExceptionMapper<CustomException> {
private static Logger logger = Logger.getLogger(CustomExceptionMapper.class.getName());
/**
* This constructor is invoked when exception is thrown, after
* resource-method has been invoked. Using @provider.
*/
public CustomExceptionMapper() {
super();
}
/**
* When exception is thrown by the jersey container.This method is invoked
*/
public Response toResponse(CustomException ex) {
logger.log(Level.SEVERE, ex.getMessage(), ex);
Response.ResponseBuilder resp = Response.status(Response.Status.BAD_REQUEST)
.entity(ex.getMessage());
return resp.build();
}
}
您还可以构造一个对象并通过CustomException将其传递给mapper,而不是消息 有一个非常简单的方法来实现这一点,如下所示
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());
如果需要添加标题、响应媒体类型或其他一些功能,ResponseBuilder提供了所有这些功能 您可以使用构造函数来完成
例如:
String msg = e.getMessage();
throw new BadRequestException(Response.status(BAD_REQUEST)
.entity(msg).build());
我认为信息可以被放入构造函数中,对吗?如果使用了exceptionMapper,它实际上会返回一个响应。我正在将消息传递给构造函数,但响应中不包含它。如果使用了exceptionMapper,则会显示传递给构造函数的消息。只需将映射程序设置为这样:public Response to Response(BadRequestException e){return Response.status(Response.status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(ExceptionUtils.getStackTrace(e)).build()}这对我很有效:
String msg = e.getMessage();
throw new BadRequestException(Response.status(BAD_REQUEST)
.entity(msg).build());