如何抛出具有特定http状态的异常?我想用403 Forbidden状态生成异常。 我使用了jax-rs库,但它只是更改了消息,状态代码仍然有500个。
if (countRequest > 10) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
邮递员的输出:
{
"timestamp": 1502582674498,
"status": 500,
"error": "Internal Server Error",
"exception": "javax.ws.rs.WebApplicationException",
"message": "HTTP 403 Forbidden",
"path": "/timesheets/late/61/cancel"
}
答案 0 :(得分:0)
您可以使用ExceptionMapper
执行此操作,如下所示:
@Provider
public class CustomExceptionMapper implements ExceptionMapper<WebApplicationException> {
@Override public Response toResponse(WebApplicationException weException) {
// grab the response from exception
Response response = weException.getResponse();
// create error object/message as you like
CustomError error = ...;
// return the custom error
return Response.status(response.getStatus()).entity(error).build();
}
}
您可以参考this教程,了解ExceptionMapper
的更多详细信息。