Hystrix - 如何注册 ExceptionMapper

Hystrix - how to register ExceptionMapper

我的 Hystrix/Feign 应用调用其他网络服务。

我想从这些 Web 服务传播错误 codes/messages。

我实现了 ErrorDecoder,它正确解码返回的异常并重新抛出它们。

不幸的是,这些异常被 HystrixRuntimeException 包装并且 JSON 返回的不是我想要的(一般错误消息,始终为 500 http 状态)。

我很可能需要一个 ExceptionMapper,我创建了一个这样的:

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

不幸的是,我的应用程序未提取此代码(调试语句在日志中不可见)。

如何在我的应用程序中注册它?

我无法使用 ExceptionMapper

我使用 ResponseEntityExceptionHandler 解决了这个问题。

代码如下:

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