Discover how a simple annotation can save you from messy error handling chaos!
Why @ExceptionHandler in controllers in Spring Boot? - Purpose & Use Cases
Imagine building a web app where every time an error happens, you have to write repetitive code in each controller method to catch and handle exceptions.
You might copy-paste try-catch blocks everywhere, making your code messy and hard to maintain.
Manually catching exceptions in every controller method leads to duplicated code and inconsistent error responses.
This makes your app fragile, harder to update, and confusing for users when errors are not handled uniformly.
The @ExceptionHandler annotation lets you centralize error handling in your controllers.
You write one method to catch specific exceptions and return clear, consistent responses automatically.
try { // controller logic } catch (Exception e) { return "Error occurred"; }
@ExceptionHandler(Exception.class) public ResponseEntity<String> handleError(Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred"); }
You can keep your controller methods clean and provide consistent, user-friendly error messages across your app.
When a user submits a form with invalid data, instead of crashing or showing a generic error, your app gracefully returns a helpful message explaining what went wrong.
Manually handling exceptions in every method is repetitive and error-prone.
@ExceptionHandler centralizes error handling in controllers.
This leads to cleaner code and better user experience with consistent error responses.
Practice
@ExceptionHandler in a Spring Boot controller?Solution
Step 1: Understand the role of @ExceptionHandler
@ExceptionHandler is used to catch exceptions that occur in controller methods to prevent the app from crashing.Step 2: Identify what @ExceptionHandler does in controllers
It allows sending user-friendly error messages and proper HTTP status codes when exceptions happen.Final Answer:
To catch and handle exceptions thrown in controller methods -> Option AQuick Check:
@ExceptionHandler catches exceptions [OK]
- Confusing @ExceptionHandler with URL mapping annotations
- Thinking it injects dependencies
- Assuming it configures database settings
Solution
Step 1: Identify the correct annotation for exception handling
@ExceptionHandler is the annotation used to mark methods that handle exceptions.Step 2: Check the method signature
The method should be annotated with @ExceptionHandler(Exception.class) and return a response, here a String view name.Final Answer:
@ExceptionHandler(Exception.class) public String handleError() { return "error"; } -> Option DQuick Check:
@ExceptionHandler syntax [OK]
- Using @RequestMapping or @GetMapping instead of @ExceptionHandler
- Misusing @Autowired annotation
- Missing the exception class in @ExceptionHandler
NullPointerException occurs?@RestController
public class MyController {
@GetMapping("/test")
public String test() {
throw new NullPointerException("Null error");
}
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleNullPointer() {
return "Null pointer error handled";
}
}Solution
Step 1: Identify the exception and handler
The controller throws NullPointerException, which is caught by the method annotated with @ExceptionHandler(NullPointerException.class).Step 2: Check the response status annotation
The handler method has @ResponseStatus(HttpStatus.BAD_REQUEST), so it sets the HTTP status to 400.Final Answer:
400 Bad Request -> Option BQuick Check:
@ResponseStatus sets HTTP code = 400 [OK]
- Assuming default 500 error without @ResponseStatus
- Confusing exception type with HTTP status
- Ignoring the @ExceptionHandler method
@RestController
public class DemoController {
@GetMapping("/demo")
public String demo() {
throw new IllegalArgumentException("Invalid argument");
}
@ExceptionHandler(NullPointerException.class)
public String handleNull() {
return "Null error";
}
}What will happen when the
/demo endpoint is called?Solution
Step 1: Identify the thrown exception
The method throws IllegalArgumentException, but the handler only catches NullPointerException.Step 2: Check if exception is handled
Since no handler matches IllegalArgumentException, Spring Boot returns a default 500 Internal Server Error.Final Answer:
The exception will not be handled and a 500 error is returned -> Option CQuick Check:
Handler mismatch causes 500 error [OK]
- Assuming handler catches all exceptions
- Thinking handler method runs for different exception types
- Expecting 404 instead of 500 error
RuntimeException for all controllers and returns a JSON error message with HTTP status 500. Which approach correctly achieves this?Solution
Step 1: Understand global exception handling
@ControllerAdvice allows defining exception handlers that apply to all controllers globally.Step 2: Define handler method for RuntimeException
Use @ExceptionHandler(RuntimeException.class) with @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) to set status 500 and return JSON response.Final Answer:
Create a class annotated with @ControllerAdvice and define a method with @ExceptionHandler(RuntimeException.class) returning a JSON response and @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR). -> Option AQuick Check:
Global handler uses @ControllerAdvice + @ExceptionHandler [OK]
- Putting handlers only inside controllers for global effect
- Using application.properties for exception handling
- Not setting proper HTTP status in handler
Ready to prove it?
Pass the test and this pattern moves unknown
