使用 @ControllerAdvice 进行 Spring 异常处理提供了集中控制,但我们必须在方法签名中添加所有抛出异常
for example
public void methodA() throws feign.FeignException,IOException,InterruptedException,ExecutionException{ //CODE }
ExceptionHandler
@ControllerAdvice
public class SpringExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value={feign.FeignException.class})
public ResponseEntity<ErrorMsg> handleFeignException(Exception ex, WebRequest request){
//CODE..
}
@ExceptionHandler(value={TimeoutException.class})
public ResponseEntity<ErrorMsg> handleTimeoutException(Exception ex, WebRequest request){
//CODE..
}
@ExceptionHandler(value={Exception.class})
public ResponseEntity<ErrorMsg> handleGenericException(Exception ex, WebRequest request){
//CODE..
}
}
这是将所有抛出异常添加到方法签名中的推荐方法吗? 如果有更好或建议的方法来声明抛出异常,请告诉我。
I have no issue with this approach but spring boot code/API Method signature looks different or lengthy.
最佳答案
如果前置条件失败,您可以从任何地方抛出异常 - 在方法内部
或在方法签名中。
处理 FeignException 可能有点棘手。我建议您阅读这篇文章 - https://source.coveo.com/2016/02/19/microservices-and-exception-handling/
关于java - 使用 @ControllerAdvice 进行 Spring 异常处理提供了集中控制,但我们必须在方法签名中添加所有抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51633853/