Hystrix - how to register ExceptionMapper

3.4k views Asked by At

My Hystrix/Feign app makes calls to other web services.

I would like to propagate error codes/messages from these web services.

I implemented ErrorDecoder, which correctly decodes exceptions returned and rethrow them.

Unfortunately these Exceptions are wrapped by HystrixRuntimeException and the JSON returned in not what I want (generic error message, always 500 http status).

Most likely I need an ExceptionMapper, I created one like this:

@Provider
public class GlobalExceptionHandler implements
    ExceptionMapper<Throwable> {

@Override
public Response toResponse(Throwable e) {
    System.out.println("ABCD 1");
    if(e instanceof HystrixRuntimeException){
        System.out.println("ABCD 2");
        if(e.getCause() != null && e.getCause() instanceof HttpStatusCodeException)
        {
            System.out.println("ABCD 3");
            HttpStatusCodeException exc = (HttpStatusCodeException)e.getCause();
            return Response.status(exc.getStatusCode().value())
                    .entity(exc.getMessage())
                    .type(MediaType.APPLICATION_JSON).build();
        }
    }
    return Response.status(500).entity("Internal server error").build();
}
}

Unfortunately this code is not being picked-up by my application (debug statements are not visible in logs).

How could I register it with my Application?

1

There are 1 answers

0
FazoM On BEST ANSWER

I couldn't make use of an ExceptionMapper.

I solved this problem using ResponseEntityExceptionHandler.

Here is the code:

@EnableWebMvc
@ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(HystrixRuntimeException.class)
    @ResponseBody
    ResponseEntity<String> handleControllerException(HttpServletRequest req, Throwable ex) {
        if(ex instanceof HystrixRuntimeException) {
            HttpStatusCodeException exc = (HttpStatusCodeException)ex.getCause();
            return new ResponseEntity<>(exc.getResponseBodyAsString(), exc.getStatusCode());
        }
        return new ResponseEntity<String>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}