简体   繁体   English

Hystrix - 如何注册ExceptionMapper

[英]Hystrix - how to register ExceptionMapper

My Hystrix/Feign app makes calls to other web services. 我的Hystrix/Feign应用程序调用其他Web服务。

I would like to propagate error codes/messages from these web services. 我想传播来自这些Web服务的错误代码/消息。

I implemented ErrorDecoder , which correctly decodes exceptions returned and rethrow them. 我实现了ErrorDecoder ,它正确解码返回的异常并重新抛出它们。

Unfortunately these Exceptions are wrapped by HystrixRuntimeException and the JSON returned in not what I want (generic error message, always 500 http status). 不幸的是,这些异常被HystrixRuntimeException包装,并且返回的JSON不是我想要的(通用错误消息,总是500 http状态)。

Most likely I need an ExceptionMapper , I created one like this: 我很可能需要一个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();
}
}

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 . 我无法使用ExceptionMapper

I solved this problem using ResponseEntityExceptionHandler . 我使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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