Handling Errors in Spring Boot Controllers with @ExceptionHandler
📖 Scenario: You are building a simple Spring Boot web application that manages a list of books. Sometimes, users might request a book that does not exist. You want to handle such errors gracefully by showing a friendly error message instead of a server error.
🎯 Goal: Learn how to use @ExceptionHandler in a Spring Boot controller to catch exceptions and return a custom error response.
📋 What You'll Learn
Create a custom exception class called BookNotFoundException
Create a controller class called BookController with a method to get a book by its ID
Add a method in BookController annotated with @ExceptionHandler(BookNotFoundException.class) to handle the exception
Return a simple error message string from the exception handler method
💡 Why This Matters
🌍 Real World
Handling errors gracefully in web applications improves user experience by showing clear messages instead of confusing errors.
💼 Career
Knowing how to use @ExceptionHandler is essential for backend developers working with Spring Boot to build robust and user-friendly APIs.
Progress0 / 4 steps
1
Create the custom exception class
Create a public class called BookNotFoundException that extends RuntimeException. Add a constructor that accepts a String message and passes it to the superclass constructor.
Spring Boot
Hint
Think of BookNotFoundException as a special error you create to say "This book was not found." It should extend RuntimeException so Spring can catch it easily.
2
Create the BookController with a sample data map
Create a class called BookController annotated with @RestController. Inside it, create a Map<Integer, String> called books initialized with these entries: 1: "Spring Boot Guide", 2: "Java Basics", 3: "REST API Design".
Spring Boot
Hint
Use @RestController to make this class a web controller. Use Map.of to create a simple fixed map of book IDs to titles.
3
Add a method to get a book by ID and throw exception if not found
Inside BookController, add a method getBookById annotated with @GetMapping("/books/{id}"). It takes an @PathVariable int id and returns the book title from books. If the book ID is not in the map, throw a new BookNotFoundException with message "Book not found with id: " + id.
Spring Boot
Hint
Use @GetMapping to map the URL. Check if the book ID exists in the map. If not, throw your custom exception.
4
Add an @ExceptionHandler method to handle BookNotFoundException
Inside BookController, add a method annotated with @ExceptionHandler(BookNotFoundException.class). This method should take a BookNotFoundException parameter and return a String with the exception's message.
Spring Boot
Hint
The @ExceptionHandler method catches your custom exception and returns its message as a response. This way, users see a friendly message instead of an error page.
Practice
(1/5)
1. What is the main purpose of using @ExceptionHandler in a Spring Boot controller?
easy
A. To catch and handle exceptions thrown in controller methods
B. To define the URL path for a controller method
C. To inject dependencies into the controller
D. To configure database connections
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 A
Quick Check:
@ExceptionHandler catches exceptions [OK]
Hint: Remember: @ExceptionHandler handles errors in controllers [OK]
Common Mistakes:
Confusing @ExceptionHandler with URL mapping annotations
Thinking it injects dependencies
Assuming it configures database settings
2. Which of the following is the correct way to declare an exception handler method in a Spring Boot controller?
easy
A. @RequestMapping(Exception.class) public String handleError() { return "error"; }
B. @GetMapping(Exception.class) public String handleError() { return "error"; }
C. @Autowired(Exception.class) public String handleError() { return "error"; }
D. @ExceptionHandler(Exception.class) public String handleError() { return "error"; }
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 D
Quick Check:
@ExceptionHandler syntax [OK]
Hint: Use @ExceptionHandler with exception class to handle errors [OK]
Common Mistakes:
Using @RequestMapping or @GetMapping instead of @ExceptionHandler
Misusing @Autowired annotation
Missing the exception class in @ExceptionHandler
3. Given the following controller code snippet, what will be the HTTP status code returned when a 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";
}
}
medium
A. 200 OK
B. 400 Bad Request
C. 500 Internal Server Error
D. 404 Not Found
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 B
Quick Check:
@ResponseStatus sets HTTP code = 400 [OK]
Hint: Look for @ResponseStatus on @ExceptionHandler method [OK]
Common Mistakes:
Assuming default 500 error without @ResponseStatus
Confusing exception type with HTTP status
Ignoring the @ExceptionHandler method
4. Consider this controller code snippet:
@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?
medium
A. The exception will be handled by handleNull method
B. The response will be "Null error" with HTTP 200
C. The exception will not be handled and a 500 error is returned
D. The server will return HTTP 404 Not Found
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 C
Quick Check:
Handler mismatch causes 500 error [OK]
Hint: Handler must match exception type exactly [OK]
Common Mistakes:
Assuming handler catches all exceptions
Thinking handler method runs for different exception types
Expecting 404 instead of 500 error
5. You want to create a global exception handler in Spring Boot that catches RuntimeException for all controllers and returns a JSON error message with HTTP status 500. Which approach correctly achieves this?
hard
A. Create a class annotated with @ControllerAdvice and define a method with @ExceptionHandler(RuntimeException.class) returning a JSON response and @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR).
B. Add @ExceptionHandler(RuntimeException.class) method inside each controller class returning a view name.
C. Use @RestController on a class with @ExceptionHandler(Exception.class) returning a String message.
D. Configure exception handling in application.properties file.
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 A
Quick Check:
Global handler uses @ControllerAdvice + @ExceptionHandler [OK]
Hint: Use @ControllerAdvice for global exception handling [OK]
Common Mistakes:
Putting handlers only inside controllers for global effect
Using application.properties for exception handling
Not setting proper HTTP status in handler
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.