Search code examples
resteasy

Global custom exception handler in 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> 

Solution

  • 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.