你可以拋出一個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。
public Entity getEntityWithOptions(@PathParam("id") String id,
@QueryParam("option") String optValue)
throws CustomException {
if (optValue != null) {
// Option is an enum
try {
Option option = Option.valueOf(optValue);
} catch (IllegalArgumentException e) {
throw new CustomException(e.getMessage(),e);
}
return new Entity(option);
}
return new Entity();
}
除了消息外,還可以構造一個對象並通過CustomException將其傳遞給映射器。
我認爲消息可以放進構造函數,對不對?如果使用了exceptionMapper,它實際上會返回一個Response。 – Cuero
我將消息傳遞給構造函數,但響應不包含它。 – dabadaba
如果使用exceptionMapper,則會顯示傳遞給構造函數的消息。只需使映射器如下所示:public Response toResponse(BadRequestException e){return Response.status(Response.Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(ExceptionUtils.getStackTrace(e))。build();} – Cuero