Spring Boot Default Exception Handling

https://www.javaguides.net/2021/10/spring-boot-exception-handling-example.html

  • By default, if there is no @ExceptionHandler for the thrown exception, Spring Boot will provide a basic error page or JSON response containing the error details. 

Postman JSON response


Custom Exception

  • If existing exceptions and error messages are enough to display the error, custom exception is not needed

We first create a custom exception

// ResourceNotFoundException.java

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    private String resourceName;
    private String fieldName;
    private Long fieldValue;
    public ResourceNotFoundException(String resourceName, String fieldName, Long fieldValue) {
        super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue));
        this.resourceName = resourceName;
        this.fieldName = fieldName;
        this.fieldValue = fieldValue;
    }
}

Then we can directly throw it

// UserService.java

public UserDto getUserById(Long id) {
    return UserMapper.mapUserToUserDto(userRepository.findById(id).orElseThrow(
        () -> new ResourceNotFoundException("User", "Id", id))
    );
}

Our custom exception is thrown, and HTTP Status code is 404.

 

Postman response


Exception Handler

@ExceptionHandler annotation

  • Annotation used to handle specific exception types and send the custom response to the client

Under controller, we can add exception handler function to handle exceptions thrown

// UserController.java

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException exception) {
    return ResponseEntity.status(404).body(exception.getMessage());
}

Then it will handle the exception thrown and return the response entity as we want.

Postman response


Global Exception Handler

@ControllerAdvice annotation

  • Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder or @ModelAttribute methods to be shared across multiple @Controller classes
  • By using this, we can consolidate our scattered @ExceptionHandler across different @Controller's 
// GlobalExceptionHandler.java

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException exception) {
        return ResponseEntity.status(404).body(exception.getMessage());
    }
}

 

'Spring' 카테고리의 다른 글

Spring Data JPA - Custom Query Methods  (0) 2023.10.30
Spring Validation  (0) 2023.09.18
DTO (Data Transfer Object)  (0) 2023.09.14
Spring Data JPA Repository  (0) 2023.09.01
Spring Data JPA Entity  (0) 2023.09.01

+ Recent posts