【问题标题】:Catch all Exceptions and also return custom Errors in Jersey捕获所有异常并返回 Jersey 中的自定义错误
【发布时间】:2014-11-07 07:40:19
【问题描述】:

我想在球衣休息服务中捕获所有意外异常。 因此我写了一个 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();
    }
}

映射器确实捕获了所有异常。因此我不能写:

public MyResult getById(@PathParam("id")) {
    if (checkAnyThing) {
        return new MyResult();
    }
    else {
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
}

这被映射器捕获。现在我必须写:

public Response getById(@PathParam("id") {
    if (checkAnyThing) { {
        return Response.ok().entity(new MyResult()).build();
    }
    else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}

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

【问题讨论】:

    标签: java jersey jax-rs jersey-2.0


    【解决方案1】:

    WebApplicationException 有一个getResponse,我们可以从中得到Response。所以你可以在你的映射器中检查WebApplicationException。也许像

    @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;
    }
    

    这样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
    

    话虽如此,我们可以在代码中显式抛出任何这些异常,只是为了赋予它更多语义价值。

    一般来说,上面的例子可能是不必要的,除非你想改变响应消息/状态代码,从上面的表格中可以看出,异常的层次结构已经有了一些一般的映射。而且在大多数情况下,意外异常已经映射到InternalServerErrorException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2015-07-14
      • 2023-03-18
      • 2012-06-23
      相关资源
      最近更新 更多