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