@ExceptionHandler in Spring: What It Is and How It Works
@ExceptionHandler is a Spring annotation used to define methods that handle specific exceptions thrown in controller classes. It lets you catch errors and return custom responses without crashing the app.How It Works
Imagine your Spring app is like a restaurant kitchen. Sometimes, mistakes happen, like burning a dish or running out of ingredients. Instead of letting the whole kitchen shut down, you want a way to handle these problems smoothly.
@ExceptionHandler works like a special helper in your kitchen who knows how to fix certain problems when they happen. When an error (exception) occurs in your controller, Spring looks for a method marked with @ExceptionHandler that matches the error type. It then runs that method to handle the problem gracefully, like showing a friendly message to the user instead of a confusing error.
This keeps your app running smoothly and helps users understand what went wrong without seeing technical details.
Example
This example shows a controller with a method that throws an exception and another method that handles it using @ExceptionHandler.
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping("/test") public String test() { throw new IllegalArgumentException("Invalid argument provided"); } @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) { return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.BAD_REQUEST); } }
When to Use
Use @ExceptionHandler when you want to catch and manage errors that happen inside your Spring controllers. It helps you provide clear, user-friendly error messages or responses instead of letting the app crash or show confusing stack traces.
Common real-world uses include handling invalid user input, missing data, or unauthorized access. For example, if a user sends wrong data, you can catch that error and return a helpful message explaining what went wrong.
Key Points
@ExceptionHandlermethods catch exceptions thrown in controller methods.- They allow custom error responses without crashing the app.
- You can handle multiple exception types by specifying them in the annotation.
- Helps improve user experience by showing friendly error messages.
- Can be used in a controller or a global controller advice class.
Key Takeaways
@ExceptionHandler catches and handles exceptions in Spring controllers.