Restaurant Not Found Exception
In our restaurant update functionality, we need to handle situations where a user attempts to update a restaurant that doesn't exist.
Let's create a dedicated exception and handler to manage this scenario effectively.
Custom Exception Creation
While we've previously used Optional to handle missing restaurants, now we're retrieving a restaurant as a part of an update, so we'll use a dedicated exception to communicate the specifics of the error.
Here's our custom exception class:
package com.devtiro.restaurant.exceptions;
public class RestaurantNotFoundException extends BaseException {
public RestaurantNotFoundException() {
}
public RestaurantNotFoundException(String message) {
super(message);
}
public RestaurantNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public RestaurantNotFoundException(Throwable cause) {
super(cause);
}
}Exception Handler Implementation
To manage our new exception, we'll add a handler to our existing ErrorController class:
@ControllerAdvice
public class ErrorController {
// ... existing handlers ...
@ExceptionHandler(RestaurantNotFoundException.class)
public ResponseEntity<ErrorDto> handleRestaurantNotFoundException(RestaurantNotFoundException ex) {
log.error("Caught RestaurantNotFoundException", ex);
ErrorDto errorDto = ErrorDto.builder()
.status(HttpStatus.NOT_FOUND.value())
.message("The specified restaurant wasn't found")
.build();
return new ResponseEntity<>(errorDto, HttpStatus.NOT_FOUND);
}
}Summary
- Created
RestaurantNotFoundExceptionfor handling non-existent restaurants - Added exception handler to return HTTP 404 responses