简体   繁体   中英

Hystrix - how to register ExceptionMapper

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?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM