I'm working with spring boot and I'm dealing with a good way to handle exceptions:
I have this case where interact with a repository to get a product. But what about if there is a connection issue with the DB, I'm not going to catch that exception
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);
}
I have a controller advice to catch the exception and return a nice response:
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({NotFoundException.class})
public ResponseEntity<Error> handleNotFoundException(HttpServletRequest request, Exception exception) {
.....
}
I think I could do something like this:
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);
That worked but it looks weird since I'm throwing NotFoundException twice. Any idea?