我正在使用spring boot,并且正在处理一种处理异常的好方法:
我有这种与存储库交互以获取产品的案例。但是如果数据库存在连接问题怎么办,我不会捕捉到那个异常
Product product = productRepository.findById(productId)
.orElseThrow(() -> new NotFoundException("Could not find a product"));
try {
// Product logic
} catch(Exception e) {
throw new ProductException(String.format("Error getting product productId=%s. Exception message: %s",
productId, e.getMessage()), e);
}
我有一个控制器建议来捕获异常并返回一个很好的响应:
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({NotFoundException.class})
public ResponseEntity<Error> handleNotFoundException(HttpServletRequest request, Exception exception) {
.....
}
我想我可以做这样的事情:
try {
Product product = productRepository.findById(productId)
.orElseThrow(() -> new NotFoundException("Could not find a product"));
} catch(NotFoundException e) {
throw new NotFoundException(e.getMessage())
} catch(Exception e) {
throw new ProductException(String.format("Error getting product productId=%s. Exception message: %s",
productId, e.getMessage()), e);
这行得通,但看起来很奇怪,因为我两次抛出 NotFoundException。任何想法?