我想在球衣休息服务中抓住所有意想不到的例外情况.因此我写了一个ExceptionMapper:
@Provider
public class ExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> {
private static Logger logger = LogManager.getLogManager().getLogger(ExceptionMapper.class.getName());
@Override
public Response toResponse(Exception e) {
logger.log(Level.SEVERE, e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal error").type("text/plain").build();
}
}
Run Code Online (Sandbox Code Playgroud)
映射器捕获所有异常.所以我写不出来:
public MyResult getById(@PathParam("id")) {
if (checkAnyThing) {
return new MyResult();
}
else {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
Run Code Online (Sandbox Code Playgroud)
这是由Mapper捕获的.现在我要写:
public Response getById(@PathParam("id") {
if (checkAnyThing) { {
return Response.ok().entity(new MyResult()).build();
}
else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
Run Code Online (Sandbox Code Playgroud)
这是捕获所有意外异常并正确返回错误(错误代码)的正确方法吗?或者还有其他(更正确的)方式吗?