捕获所有异常并返回Jersey中的自定义错误 [英] Catch all Exceptions and also return custom Errors in Jersey

查看:183
本文介绍了捕获所有异常并返回Jersey中的自定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在球衣休息服务中捕捉所有意想不到的例外情况。
因此我写了一个ExceptionMapper:

I want to catch all unexpected Exceptions in a jersey rest service. Therefore i wrote an 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();
    }
}

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

The mapper catches really all exceptions. Therefore i can't write:

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

这是Mapper捕获的。现在我必须写:

This is catched by the Mapper. Now i have to write:

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

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

Is this the correct way to catch all unexpected exceptions and also return errors (error codes) in jersey? Or is there any other (more correct) way?

推荐答案

WebApplicationException getResponse 我们可以从中获得响应。所以你可以检查<$ c您的映射器中有$ c> WebApplicationException 。也许类似

WebApplicationException has a getResponse from which we can get the Response. So you can check for a WebApplicationException in your mapper. Maybe something like

@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抛出的异常,其中包含预定义的响应/状态代码。

That way an instance of WebApplicationException thrown will just return the default response. This will actually handle some other exceptions also, not thrown explictly by your application. WebApplicationException has a few other exception under its hierarchy that are thrown by JAX-RS, for which predefined response/status codes are wrapped.

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

话虽如此,我们可以明确地抛出任何一个我们的代码中的这些异常,只是为了赋予它更多的语义价值。

That being said, we could explicitly throw any of these exceptions in our code, just to give it more semantic value.

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

Generally speaking though, the example above may be unnecessary, unless you want to alter the response message/status code, as one can from the table above, the hierarchy of exceptions already have some general mapping. And in most cases, unexpected exceptions will already be mapped to InternalServerErrorException

这篇关于捕获所有异常并返回Jersey中的自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆