我正在使用Netflix的openFeign与外部API建立REST通信。我已经使用Feign errorDecoder处理假异常。
public class MyErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultErrorDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() == 404) {
return new MyNotFoundException();
return defaultErrorDecoder.decode(methodKey, response);
}}
要在Spring之前获取MyErrorDecoder,我已将其放在ApplicationContext中:
@Bean
public MyErrorDecoder myErrorDecoder() {
return new MyErrorDecoder();
}
我还实现了ExceptionTranslator类来处理这些异常。
@ControllerAdvice
public class ExceptionTranslator {
private static final Logger log = LoggerFactory.getLogger(ExceptionTranslator.class);
@ExceptionHandler(MyNotFoundException.class)
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorData myNotFoundExc(MyNotFoundException exception){
log.warn(exception.getMessage(), exception);
return new ErrorData(exception.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorData processRuntimeException(Exception exception){
log.error(exception.getMessage(), exception);
return new ErrorData(exception.getMessage());
}
}
每当应用程序抛出MyNotFoundException
时,它就会被@ExceptionHandler(Exception.class)
而不是@ExceptionHandler(MyNotFoundException.class)
消耗。
当我删除@ExceptionHandler(Exception.class)
时,它可以按我的意愿工作。
有人知道如何实现我期望的行为吗?