[英]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.