In Week 5, we secured our Spring Boot APIs using JWT authentication and role-based access.
Now, in Week 6, we’ll focus on handling errors gracefully and implementing professional logging — two crucial aspects of production-ready applications.
By the end of this article, your application will catch errors centrally, provide clean API responses, and have a robust logging system for debugging and monitoring.
Why Error Handling & Logging Matter
❌ Without proper error handling:
APIs return messy stack traces
Debugging is difficult
User experience suffers
❌ Without logging:
Hard to monitor production issues
No insights into user behavior
Difficult to troubleshoot crashes
✅ Proper handling and logging provide:
Centralized error management
Consistent API responses
Easy debugging and monitoring
Professional, maintainable code
Step 1: Global Exception Handling with @ControllerAdvice
Spring Boot allows centralized exception handling using @ControllerAdvice:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiError> handleResourceNotFound(ResourceNotFoundException ex) {
ApiError error = new ApiError(HttpStatus.NOT_FOUND, ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidationException(MethodArgumentNotValidException ex) {
String message = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.joining(", "));
ApiError error = new ApiError(HttpStatus.BAD_REQUEST, message);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiError> handleGenericException(Exception ex) {
ApiError error = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}