gpt4 book ai didi

spring-mvc - 如何捕获 FeignClient 异常

转载 作者:行者123 更新时间:2023-12-03 16:29:40 24 4
gpt4 key购买 nike

我 try catch 从 FeignClient 连接的另一个微服务收到的异常。我制作了自定义的 ErrorDecoder,并且

public class CustomErrorDecoder implements ErrorDecoder {

private final Logger log = LoggerFactory.getLogger(getClass());

private final ErrorDecoder defaultErrorDecoder = new Default();

@Override
public Exception decode(String methodKey, Response response) {

if (response.status() >= 400 && response.status() <= 499) {
log.info("----------------- "+methodKey+" , "+response.status()+" , "+ response.reason());
return new RestApiException(99,99,"");
}
return defaultErrorDecoder.decode(methodKey, response);
}
}

其中 RestApiException 扩展了 Exception。
@ControllerAdvice
public class GlobalControllerAdvice {

private final Logger log = LoggerFactory.getLogger(getClass());

@ExceptionHandler(RestApiException.class)
public ResponseEntity<RestApiException> handleException(RestApiException exception, HttpServletRequest req) {
log.error("Sending error to client ( "+req.getUserPrincipal().getName()+" ) \"{}\"", exception.getErrMsg());
return new ResponseEntity<RestApiException>(exception, exception.getStatus());
}

@ExceptionHandler(Throwable.class)
public ResponseEntity<RestApiException> handleException(Throwable throwable, HttpServletRequest req) {
RestApiException exception=new RestApiException(HttpStatus.INTERNAL_SERVER_ERROR, 100, 100,
throwable.getMessage());
return handleException(exception, req);
}

结果,当我得到 <--- HTTP/1.1 400 Bad Request (5380ms)
我有默认的错误消息

HttpStatus.INTERNAL_SERVER_ERROR, 100, 100,
throwable.getMessage());

但不是 expexted 自定义异常,我尝试在 CustomErrorDecoder 中设置。

我做错了什么,为什么我不能调用 RetAppiException 并向其余客户端返回错误答案。

谢谢。

最佳答案

您无法使用 @ControllerAdvice 捕获 FeignClient 的异常。 .异常处理程序不会捕获由 feign 客户端、错误解码器生成的异常。

一个简单的解决方案是捕捉你的假调用,然后抛出你想要的异常。

try{
feignClient.method();
} catch(Exception ex){
//throw exceptions you want
throw new YourException();
}

然后你将能够处理它:
@ControllerAdvice
public class GlobalControllerAdvice {

private final Logger log = LoggerFactory.getLogger(getClass());

@ExceptionHandler(YourException.class)
public ResponseEntity<RestApiException> handleException(RestApiException exception, HttpServletRequest req) {
//impl
}

}

关于spring-mvc - 如何捕获 FeignClient 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40362322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com