我的Hystrix/Feign
应用程序调用其他 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);
}
}