Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Spring Framework FAQ: Top Questions

27. How does Spring handle exception handling with @ExceptionHandler?

@ExceptionHandler is used to define methods that handle specific exceptions thrown from controller methods. It enables centralized error response logic.

📥 Example:

@ControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(ResourceNotFoundException.class)
  public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
    return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
  }
}

🏆 Expected Output:

Returns 404 status and message when ResourceNotFoundException is thrown.

🛠️ Use Cases:

  • Consistent API error response formatting.
  • Centralized logging of exceptions.