簡體   English   中英

Hystrix - 如何注冊ExceptionMapper

[英]Hystrix - how to register ExceptionMapper

我的Hystrix/Feign應用程序調用其他Web服務。

我想傳播來自這些Web服務的錯誤代碼/消息。

我實現了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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM