Global custom exception handler in resteasy

99封情书 提交于 2020-01-13 10:14:13

问题


Is it possible to make global exception handler for all unexpected errors. Because it's impossible to make all possible classes like this:

public class ExceptionHandler implements ExceptionMapper<JsonMappingException> {...}

I want something like this:

public class ExceptionHandler implements ExceptionMapper<Exception> 

回答1:


You could probably do the following:

@Provider
public class GlobalExceptionHandler implements ExceptionMapper<Exception> {
    public Response toResponse(Exception exception) {
        return Response.status(Status.INTERNAL_SERVER_ERROR)
            .entity("An error occured").type(MediaType.TEXT_PLAIN)
            .build();
    }
}

I have just tested it in RESTEasy 3.0.6.Final and it seems to work. Keep in mind that the 500 Internal Server Error status code may not always be appropriate.




回答2:


Note that although the accepted answer does catch all exceptions it will cause many other issues, eg interfering with the internal exception handling of Resteasy.

Therefore if you take this approach you should also build a custom exception mapping for each method that is important for you.

In particular this method will break the built in CORS handling, so you should create a CORS custom exception mapper if you allow CORS responses.

@Provider
public class DefaultOptionsExceptionHandler implements ExceptionMapper<DefaultOptionsMethodException> {

    @Override
    public Response toResponse(DefaultOptionsMethodException e) {
        return e.getResponse(); 
    }
}



回答3:


It seems there's no easy way to make it. I have to modify ResteasyProviderFactory which returns right ExceptionMapper. But then I should change couple classes because there's direct usage of build-in class ResteasyProviderFactory



来源:https://stackoverflow.com/questions/13857638/global-custom-exception-handler-in-resteasy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!