捕获所有异常并返回Jersey中的自定义错误

Dom*_*nic 20 java jax-rs jersey jersey-2.0

我想在球衣休息服务中抓住所有意想不到的例外情况.因此我写了一个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)

这是捕获所有意外异常并正确返回错误(错误代码)的正确方法吗?或者还有其他(更正确的)方式吗?

Pau*_*tha 30

WebApplicationException有一个getResponse我们可以得到的Response.因此,您可以WebApplicationException在映射器中检查a .也许是这样的

@Override
public Response toResponse(Throwable error) {
    Response response;
    if (error instanceof WebApplicationException) {
        WebApplicationException webEx = (WebApplicationException)error;
        response = webEx.getResponse();
    } else {
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("Internal error").type("text/plain").build();
    }
    return response;
}
Run Code Online (Sandbox Code Playgroud)

这样一个WebApplicationException抛出的实例将只返回默认响应.这实际上也会处理其他一些异常,而不是由您的应用程序显式抛出.WebApplicationException在JAX-RS抛出的层次结构下有一些其他异常,其中包含预定义的响应/状态代码.

Exception                      Status code    Description
-------------------------------------------------------------------------------
BadRequestException            400            Malformed message
NotAuthorizedException         401            Authentication failure
ForbiddenException             403            Not permitted to access
NotFoundException              404            Couldn’t find resource
NotAllowedException            405            HTTP method not supported
NotAcceptableException         406            Client media type requested 
                                                            not supported
NotSupportedException          415            Client posted media type 
                                                            not supported
InternalServerErrorException   500            General server error
ServiceUnavailableException    503            Server is temporarily unavailable 
                                                            or busy
Run Code Online (Sandbox Code Playgroud)

话虽这么说,我们可以在代码中明确地抛出任何这些异常,只是为了给它更多的语义价值.

一般来说,上面的示例可能是不必要的,除非您想要更改响应消息/状态代码,如上表所示,异常层次结构已经具有一些常规映射.在大多数情况下,意外的异常将已映射到InternalServerErrorException