Skip to content

Error handling in Spring Boot

Somkiat Puisungnoen edited this page May 13, 2026 · 3 revisions

Error handling in Spring Boot

  • Centralization
  • Consistency
  • Security

1. Define a Standard Error Response

  • POJO Class
  • Lombok
  • Java record
public class ErrorResponse {
    private int status;
    private String message;
    private long timestamp;

    // Constructors, Getters, and Setters
    public ErrorResponse(int status, String message, long timestamp) {
        this.status = status;
        this.message = message;
        this.timestamp = timestamp;
    }
}

2. Create the Global Exception Handler

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 1. Handle specific custom exceptions (e.g., ResourceNotFound)
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.NOT_FOUND.value(),
            ex.getMessage(),
            System.currentTimeMillis()
        );
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }

    // 2. Generic Catch-All: Handles any other unhandled Exception
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.INTERNAL_SERVER_ERROR.value(),
            "An unexpected error occurred: " + ex.getMessage(),
            System.currentTimeMillis()
        );
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

3. Custom exception

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) { super(message); }
}

4. Your controller/service/repository

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userRepository.findById(id)
        .orElseThrow(() -> new ResourceNotFoundException("User not found with ID: " + id));
}

5. Generic Error Response Wrappers

// A generic wrapper for error details
public class ApiError<T> {
    private String message;
    private T details; // Can hold a String, a Map, or a custom Object

    public ApiError(String message, T details) {
        this.message = message;
        this.details = details;
    }
}

Clone this wiki locally