Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global custom exception handler in resteasy

Tags:

resteasy

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> 
like image 740
Max Grigoriev Avatar asked Dec 13 '12 10:12

Max Grigoriev


2 Answers

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(); 
    }
}
like image 178
Pool Avatar answered Sep 18 '22 23:09

Pool


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.

like image 25
Christian Gürtler Avatar answered Sep 16 '22 23:09

Christian Gürtler