Exception Handling
We recently introduced the TaskNotFoundException. Let's now handle it in
the global exception handler.
Update the Global Exception Handler
When a TaskNotFoundException bubbles up to the presentation layer we want to
return a standard, helpful error message and an HTTP 400 BAD REQUEST status
code.
Let's add this handler to the GlobalExceptionHandler class:
/**
* Handles the TaskNotFoundException, returning a standardised error
* response and an HTTP 400.
* This exception is thrown when the specified task is not found.
*
* @param ex The TaskNotFoundException.
* @return The standardised error and an HTTP 400.
*/
@ExceptionHandler({TaskNotFoundException.class})
public ResponseEntity<ErrorResponseDto> handleExceptions(
TaskNotFoundException ex) {
// Create an ErrorResponseDto using a templated error message.
ErrorResponseDto errorResponseDto = new ErrorResponseDto(
String.format("Task with ID '%s' not found", ex.getId())
);
// Return the ErrorResponseDto with status HTTP 400 BAD REQUEST.
return new ResponseEntity<>(errorResponseDto, HttpStatus.BAD_REQUEST);
}With the TaskNotFoundException handled, let's now test the update task
feature in the UI!
Summary
- Added handling for the
TaskNotFoundExceptionclass.