2017-01-09 28 views
0

我的Hystrix/Feign應用程序會調用其他Web服務。Hystrix - 如何註冊ExceptionMapper

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

我實現了ErrorDecoder,它正確地解碼返回的異常並重新拋出它們。

不幸的是,這些異常是由HystrixRuntimeExceptionJSON返回不是我想要的(通用錯誤消息,總是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(); 
} 
} 

不幸的是這個代碼是沒有被拾取由我的應用程序(調試語句在日誌中可見)。

我該如何在我的應用程序中註冊?

回答

0

我無法使用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); 
    } 
}