-
Notifications
You must be signed in to change notification settings - Fork 0
Error handling in Spring Boot
Somkiat Puisungnoen edited this page May 13, 2026
·
3 revisions
- Centralization
- Consistency
- Security
- 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;
}
}
@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);
}
}
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) { super(message); }
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with ID: " + id));
}
// 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;
}
}