Exception Handling
@ControllerAdvice, @ExceptionHandler, ProblemDetail (RFC 7807), custom error responses
- Centralise all exception handling with @ControllerAdvice
- Map domain exceptions to structured JSON error responses
- Implement RFC 7807 ProblemDetail responses
Course:
Spring Boot Series Instructor: Shreyansh Prerequisites: Spring Boot REST APIs, Java Custom Exceptions, Response Entity
Table of Contents
- Classes Involved in Exception Handling
- The Exception Resolution Flow
- Default Behavior — What Happens Without Any Handler
- Taking Manual Control — Returning ResponseEntity
- Resolver 1 — ExceptionHandlerExceptionResolver
- Resolver 2 — ResponseStatusExceptionResolver
- Resolver 3 — DefaultHandlerExceptionResolver
- @ResponseStatus + @ExceptionHandler Together — The Tricky Cases
- Global Exception Handling with @ControllerAdvice
- Priority Rules — Which Handler Wins?
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Summary
Classes Involved in Exception Handling
Spring Boot uses a hierarchy of five classes to handle exceptions. Understanding each class and its role is fundamental to mastering exception handling.
Role of Each Class
| Class | Type | Role |
|---|---|---|
HandlerExceptionResolver | Interface | Defines the contract — exposes resolveException() |
HandlerExceptionResolverComposite | Helper / Orchestrator | Coordinates the three resolvers; invokes them in sequence |
ExceptionHandlerExceptionResolver | Resolver 1 | Handles @ExceptionHandler and @ControllerAdvice annotations |
ResponseStatusExceptionResolver | Resolver 2 | Handles uncaught exceptions annotated with @ResponseStatus |
DefaultHandlerExceptionResolver | Resolver 3 | Handles Spring Framework built-in exceptions (404, method not found, etc.) |
DefaultErrorAttributes | Helper / Response Builder | Builds the final error response object (timestamp, status, error, path) and sends it |
DefaultErrorAttributes builds the final response. Always keep this distinction clear.The Exception Resolution Flow
High-Level Flow
Step-by-Step Description
- Exception is thrown — either in a controller method, or the DispatcherServlet cannot even find the controller
- DispatcherServlet passes the exception to
HandlerExceptionResolverComposite - Composite (Orchestrator) tries each resolver in sequence:
- Passes to Resolver 1 (
ExceptionHandlerExceptionResolver) - Checks: was the exception handled?
- If yes → skip remaining resolvers, go to
DefaultErrorAttributes - If no → pass to Resolver 2 (
ResponseStatusExceptionResolver) - Checks again. If yes →
DefaultErrorAttributes. If no → pass to Resolver 3 - Resolver 3 (
DefaultHandlerExceptionResolver) tries to handle it
- After all resolvers complete (regardless of whether any handled it),
DefaultErrorAttributesbuilds the response:
- Sets
timestamp,status,error,message,path - Creates a
ResponseEntityand sends it to the client
DefaultErrorAttributes is always invoked — it is the final step regardless of which resolver (if any) handled the exception. If a resolver handled it, DefaultErrorAttributes uses the status and message the resolver set. If no resolver handled it, DefaultErrorAttributes uses the default status: 500 Internal Server Error.Default Behavior What Happens Without Any Handler
Example 1 Throwing a NullPointerException
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @GetMapping("/get-user")6 public String getUser() {7 throw new NullPointerException("Something is null");8 // No try-catch, no ResponseEntity returned9 }10}{
"timestamp": "2024-01-15T10:30:00.000+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/get-user"
}Who sets this response? DefaultErrorAttributes. No resolver could handle a plain NullPointerException, so the default status 500 is used.
Example 2 Throwing a Custom Exception (Without Any Handler)
◆ Custom Exception Class
1public class CustomException extends RuntimeException {2
3 private HttpStatus status;4 private String message;5
6 public CustomException(HttpStatus status, String message) {7 super(message); // Sets the parent's detailedMessage field8 this.status = status;9 this.message = message;10 }11
12 public HttpStatus getStatus() { return status; }13
14 @Override15 public String getMessage() { return message; }16}super(message) — this flows up to RuntimeException → Exception and sets the internal detailedMessage field. When the framework calls getMessage(), it returns this.
- Option B (override): Add your own String message field and override getMessage() to return it directly. This gives you full control without relying on the parent's field.◆ Controller
1@GetMapping("/get-user")2public String getUser() {3 throw new CustomException(HttpStatus.BAD_REQUEST, "Request is not correct. User ID is missing.");4}{
"timestamp": "2024-01-15T10:30:00.000+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/get-user"
}CustomException carries HttpStatus.BAD_REQUEST (400), the response shows 500. This is because no resolver recognizes or handles this custom exception. DefaultErrorAttributes uses the default 500 since the exception went unhandled through all three resolvers.
The status and message fields inside your custom exception object mean nothing to the framework unless you explicitly read them and set the response.Taking Manual Control Returning ResponseEntity
The cleanest approach: catch the exception yourself, build a ResponseEntity, and return it. The resolver framework is completely bypassed.
Error Response POJO
1public class ErrorResponse {2 private Date timestamp;3 private String message;4 private int status;5
6 public ErrorResponse(Date timestamp, String message, int status) {7 this.timestamp = timestamp;8 this.message = message;9 this.status = status;10 }11 // Getters12}Controller with Try-Catch
1@GetMapping("/get-user")2public ResponseEntity<?> getUser() {3 try {4 throw new CustomException(HttpStatus.BAD_REQUEST, "Request is not correct. User ID is missing.");5 } catch (CustomException e) {6 ErrorResponse body = new ErrorResponse(7 new Date(),8 e.getMessage(),9 e.getStatus().value()10 );11 return ResponseEntity12 .status(e.getStatus()) // HTTP 40013 .body(body); // Error response object14 } catch (Exception e) {15 ErrorResponse body = new ErrorResponse(new Date(), e.getMessage(), 500);16 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);17 }18}{
"timestamp": "2024-01-15T10:30:00.000+00:00",
"status": 400,
"message": "Request is not correct. User ID is missing."
}ResponseEntity directly from your controller or exception handler, DefaultErrorAttributes is NOT involved. You are fully in control of the response body and HTTP status. The resolver framework is bypassed entirely.Resolver 1 ExceptionHandlerExceptionResolver
This is the most important and most used resolver in real-world Spring Boot applications.
What it handles: Methods annotated with @ExceptionHandler (either at controller level or inside a @ControllerAdvice class).
Controller-Level Exception Handling
@ExceptionHandler methods placed inside a controller class apply only to exceptions thrown by methods in that same controller.
◆ Use Case 1 Basic Handler Returning a String
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @GetMapping("/get-user")6 public String getUser() {7 throw new CustomException(HttpStatus.BAD_REQUEST, "User ID is missing");8 }9
10 // Handles CustomException thrown by ANY method in THIS controller11 @ExceptionHandler(CustomException.class)12 public ResponseEntity<String> handleCustomException(CustomException e) {13 return ResponseEntity14 .status(e.getStatus())15 .body(e.getMessage()); // Returns plain string body16 }17}HTTP 400 Bad Request Body: "User ID is missing"
◆ Use Case 2 Handler Returning an Error Response Object
1@ExceptionHandler(CustomException.class)2public ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {3 ErrorResponse body = new ErrorResponse(4 new Date(),5 e.getMessage(),6 e.getStatus().value()7 );8 return ResponseEntity.status(e.getStatus()).body(body);9}HTTP 400 Bad Request
{
"timestamp": "2024-01-15T10:30:00.000+00:00",
"status": 400,
"message": "User ID is missing"
}◆ Use Case 3 Multiple Exception Handlers in One Controller
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @GetMapping("/get-user")6 public String getUser() {7 throw new CustomException(HttpStatus.BAD_REQUEST, "User ID is missing");8 }9
10 @GetMapping("/get-order")11 public String getOrder() {12 throw new IllegalArgumentException("Invalid argument provided");13 }14
15 // Handler 1 — for CustomException16 @ExceptionHandler(CustomException.class)17 public ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {18 return ResponseEntity.status(e.getStatus())19 .body(new ErrorResponse(new Date(), e.getMessage(), e.getStatus().value()));20 }21
22 // Handler 2 — for IllegalArgumentException23 @ExceptionHandler(IllegalArgumentException.class)24 public ResponseEntity<ErrorResponse> handleIllegalArgument(IllegalArgumentException e) {25 return ResponseEntity.status(HttpStatus.BAD_REQUEST)26 .body(new ErrorResponse(new Date(), e.getMessage(), 400));27 }28}◆ Use Case 4 One Handler for Multiple Exception Types
If multiple exceptions result in the same response structure, consolidate them:
1// Handles BOTH CustomException AND IllegalArgumentException2@ExceptionHandler({CustomException.class, IllegalArgumentException.class})3public ResponseEntity<ErrorResponse> handleMultipleExceptions(Exception e) {4 // Must use parent type 'Exception' since we're handling multiple types5 return ResponseEntity.status(HttpStatus.BAD_REQUEST)6 .body(new ErrorResponse(new Date(), e.getMessage(), 400));7}@ExceptionHandler handles multiple exception types, the method parameter must use a common parent type (e.g., Exception) since only one parameter is allowed and it must accommodate all specified types. If handling a single exception type, you can use the exact exception class as the parameter.◆ Use Case 5 Handler Without Returning ResponseEntity (Using HttpServletResponse)
1@ExceptionHandler(CustomException.class)2public void handleCustomException(CustomException e, HttpServletResponse response) throws IOException {3 response.sendError(e.getStatus().value(), e.getMessage());4 // Does NOT return a ResponseEntity5 // Sets status and message into the response attributes6 // DefaultErrorAttributes will pick these up and build the response7}What happens:
- The exception handler sets the status and message in the
HttpServletResponse - Since no
ResponseEntityis returned,DefaultErrorAttributestakes over DefaultErrorAttributesreads the status (400) and message from the response and builds a proper JSON error response
Output:
1{2 "timestamp": "2024-01-15T10:30:00.000+00:00",3 "status": 400,4 "error": "Bad Request",5 "message": "User ID is missing",6 "path": "/api/get-user"7}Supported Parameters for `@ExceptionHandler` Methods
The ExceptionHandlerExceptionResolver knows how to resolve and inject specific parameter types into @ExceptionHandler methods. You can use any combination, in any order:
| Parameter Type | What It Provides |
|---|---|
SomeException (exact or parent) | The thrown exception object |
HttpServletRequest | The incoming HTTP request |
HttpServletResponse | The outgoing HTTP response — use to set status/message manually |
1// All three — any order is valid2@ExceptionHandler(CustomException.class)3public void handle(HttpServletRequest req, CustomException e, HttpServletResponse res) { ... }4
5// Just the exception6@ExceptionHandler(CustomException.class)7public ResponseEntity<?> handle(CustomException e) { ... }8
9// Exception and response10@ExceptionHandler(CustomException.class)11public void handle(CustomException e, HttpServletResponse res) { ... }String, Integer) to an @ExceptionHandler method. The resolver only knows how to inject the supported types listed above. Unsupported parameters will cause the handler not to be invoked at all.Resolver 2 ResponseStatusExceptionResolver
What it handles: Uncaught exceptions (exceptions not handled by Resolver 1) whose class is annotated with @ResponseStatus.
ResponseStatusExceptionResolver only processes exceptions that have passed through Resolver 1 without being handled. It reads the @ResponseStatus annotation from the exception class itself, not from any handler method.Example Basic `@ResponseStatus` on Custom Exception
1@ResponseStatus(HttpStatus.BAD_REQUEST) // Annotate the exception class2public class CustomException extends RuntimeException {3
4 public CustomException(String message) {5 super(message);6 }7}1@GetMapping("/get-user")2public String getUser() {3 throw new CustomException("User ID is missing");4 // No @ExceptionHandler for this — goes to Resolver 25}Flow:
- Exception thrown → Resolver 1 has no
@ExceptionHandlerfor it → passes to Resolver 2 - Resolver 2 checks the exception class for
@ResponseStatus→ finds it - Resolver 2 calls
response.sendError(400)— sets status in the response DefaultErrorAttributesreads status (400), builds response
Output:
1{2 "timestamp": "2024-01-15T10:30:00.000+00:00",3 "status": 400,4 "error": "Bad Request",5 "path": "/api/get-user"6}Example `@ResponseStatus` with `reason` (Message)
1@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Invalid request sent")2public class CustomException extends RuntimeException {3
4 public CustomException(String message) {5 super(message);6 }7}{
"timestamp": "2024-01-15T10:30:00.000+00:00",
"status": 400,
"error": "Bad Request",
"message": "Invalid request sent"
}reason is provided in @ResponseStatus, it takes priority as the message over the exception's own message (set via super(message)). If reason is not provided, DefaultErrorAttributes uses its default message for the status code.Resolver 3 DefaultHandlerExceptionResolver
This resolver handles Spring Framework's own built-in exceptions — exceptions thrown by the framework itself when it cannot process a request. These are not your application-level exceptions.
Examples of Exceptions It Handles
| Exception | HTTP Status | Typical Cause |
|---|---|---|
NoResourceFoundException | 404 Not Found | No controller mapped to the requested URL |
HttpRequestMethodNotSupportedException | 405 Method Not Allowed | Wrong HTTP method used (e.g., GET on a POST endpoint) |
HttpMediaTypeNotSupportedException | 415 Unsupported Media Type | Wrong Content-Type header |
MissingServletRequestParameterException | 400 Bad Request | Required @RequestParam is missing |
MethodArgumentNotValidException | 400 Bad Request | @Valid / @Validated bean validation failure |
Example Calling a Non-Existent API
1GET /api/get-user/999999 (no controller mapped to this path)Flow:
- DispatcherServlet cannot find a controller for this URL
- Exception passed to Composite → Resolver 1 → Resolver 2 → Resolver 3
- Resolver 3 recognizes
NoResourceFoundExceptionas a Spring framework exception - Sets status 404 and message in the response
DefaultErrorAttributesbuilds the final response
Output:
1{2 "timestamp": "2024-01-15T10:30:00.000+00:00",3 "status": 404,4 "error": "Not Found",5 "message": "No static resource api/get-user/999999",6 "path": "/api/get-user/999999"7}@ResponseStatus + @ExceptionHandler Together The Tricky Cases
This is one of the most confusing areas and a common source of bugs. Read carefully.
Tricky Case 1 @ExceptionHandler Returning ResponseEntity + @ResponseStatus on Method
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @GetMapping("/get-user")6 public String getUser() {7 throw new CustomException(HttpStatus.BAD_REQUEST, "User ID is missing");8 }9
10 // @ResponseStatus says: bad request, "Invalid request"11 // Method body says: ResponseEntity with 403 FORBIDDEN and "You are not authorized"12 @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Invalid request")13 @ExceptionHandler(CustomException.class)14 public ResponseEntity<String> handleCustomException(CustomException e) {15 return ResponseEntity16 .status(HttpStatus.FORBIDDEN) // 40317 .body("You are not authorized");18 }19}What output do you expect? 403 Forbidden or 400 Bad Request?
Actual Output:
1HTTP 400 Bad Request2Body: "Invalid request"Why?
Key insight: @ResponseStatus on an @ExceptionHandler method is not processed by ResponseStatusExceptionResolver. It is processed by Spring Framework's internal ServletInvocableHandlerMethod after the handler method executes. It overrides whatever the ResponseEntity contained.
@ResponseStatus and @ExceptionHandler are on the same method, @ResponseStatus always wins — it overrides the status and message set inside the ResponseEntity. The second resolver (ResponseStatusExceptionResolver) is not involved at all.Tricky Case 2 @ExceptionHandler Using `response.sendError()` + @ResponseStatus on Method
1@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Invalid request sent")2@ExceptionHandler(CustomException.class)3public void handleCustomException(CustomException e, HttpServletResponse response) throws IOException {4 response.sendError(HttpStatus.FORBIDDEN.value(), "User ID is missing");5 // Sets 403 and message — then COMMITS the response6}What output do you expect? 403 Forbidden or 400 Bad Request?
Actual Output:
1HTTP 500 Internal Server ErrorWhy?
response.sendError() commits the HTTP response immediately. Once a response is committed, it cannot be modified. When Spring Framework tries to apply @ResponseStatus afterward (calling sendError again), the underlying system throws an exception because you cannot write to an already-committed response. This exception propagates and ultimately results in a 500.
response.sendError() inside an @ExceptionHandler method that also has @ResponseStatus. The commit from sendError makes the second sendError (from @ResponseStatus) throw an exception, resulting in 500.Rules When Combining @ResponseStatus and @ExceptionHandler
| Combination | Result | Recommendation |
|---|---|---|
@ExceptionHandler returns ResponseEntity + @ResponseStatus on method | @ResponseStatus overrides the ResponseEntity status and message | ⚠️ Avoid — confusing; pick one |
@ExceptionHandler uses response.sendError() + @ResponseStatus on method | 500 Internal Server Error | ❌ Never do this |
@ExceptionHandler returns ResponseEntity only (no @ResponseStatus) | ResponseEntity status and body are used | ✅ Recommended |
@ResponseStatus on exception class + no @ExceptionHandler | ResponseStatusExceptionResolver handles it | ✅ Fine for simple cases |
@ResponseStatus set the status/message, or let the @ExceptionHandler method body do it via ResponseEntity or response.sendError(). Never both.Global Exception Handling with @ControllerAdvice
The Problem With Controller-Level Handlers
If you have 100 controllers and each can throw CustomException, you would have to write the same @ExceptionHandler method in every single controller. This is massive code duplication.
Solution @ControllerAdvice
@ControllerAdvice marks a class as a global exception handler. @ExceptionHandler methods inside it apply to all controllers in the application.
1@ControllerAdvice2public class GlobalExceptionHandler {3
4 @ExceptionHandler(CustomException.class)5 public ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {6 ErrorResponse body = new ErrorResponse(new Date(), e.getMessage(), e.getStatus().value());7 return ResponseEntity.status(e.getStatus()).body(body);8 }9
10 @ExceptionHandler(IllegalArgumentException.class)11 public ResponseEntity<ErrorResponse> handleIllegalArgument(IllegalArgumentException e) {12 ErrorResponse body = new ErrorResponse(new Date(), e.getMessage(), 400);13 return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);14 }15
16 // Catch-all for any unhandled exception17 @ExceptionHandler(Exception.class)18 public ResponseEntity<ErrorResponse> handleGenericException(Exception e) {19 ErrorResponse body = new ErrorResponse(new Date(), "An unexpected error occurred", 500);20 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);21 }22}This single class handles exceptions from UserController, OrderController, InvoiceController, and every other controller — no duplication.
Priority Rules Which Handler Wins?
Rule 1 Controller-Level Before Global
If the same exception has a handler both inside the throwing controller AND in @ControllerAdvice, the controller-level handler always takes priority.
1// GlobalExceptionHandler.java (@ControllerAdvice)2@ExceptionHandler(CustomException.class)3public ResponseEntity<?> globalHandler(CustomException e) {4 return ResponseEntity.status(e.getStatus()).body("From GLOBAL handler");5}1// UserController.java2@ExceptionHandler(CustomException.class)3public ResponseEntity<?> controllerHandler(CustomException e) {4 return ResponseEntity.status(e.getStatus()).body("From CONTROLLER handler");5}6
7@GetMapping("/get-user")8public String getUser() {9 throw new CustomException(HttpStatus.BAD_REQUEST, "User ID is missing");10}@ControllerAdvice
public class GlobalExceptionHandler {
// Exact match
@ExceptionHandler(CustomException.class)
public ResponseEntity<?> handleCustom(CustomException e) {
return ResponseEntity.badRequest().body("Exact: " + e.getMessage());
}
// Parent match — also applicable since CustomException extends RuntimeException
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<?> handleRuntime(RuntimeException e) {
return ResponseEntity.badRequest().body("Parent: " + e.getMessage());
}
}When CustomException is thrown: handleCustom() is invoked — exact match wins. When any other RuntimeException is thrown: handleRuntime() is invoked.
Priority Hierarchy Summary
Key Observations
- Resolvers run in sequence — Resolver 1 → Resolver 2 → Resolver 3. Once one handles it, the rest are skipped.
DefaultErrorAttributesalways runs last — it reads whatever status and message were set by the resolver (or uses defaults) and builds the final JSON response.
- Default status is 500 — if no resolver handles the exception,
DefaultErrorAttributesuses 500 as the default.
- Returning
ResponseEntitybypassesDefaultErrorAttributes— when an@ExceptionHandlermethod returns aResponseEntity, the resolver creates the response directly andDefaultErrorAttributesis not needed.
response.sendError()commits the response — once committed, no further writes are possible. Using it alongside@ResponseStatuson the same method causes a 500.
- *
ResponseStatusExceptionResolveronly handles uncaught exceptions* — if Resolver 1 already handled it, Resolver 2 is never invoked, even if the exception class has@ResponseStatus.
@ResponseStatuson an@ExceptionHandlermethod is processed by Spring Framework, not by Resolver 2 — this override happens insideServletInvocableHandlerMethodafter the handler executes.
@ControllerAdviceis truly global — one class handles exceptions from the entire application.
- Controller-level handlers have higher priority than
@ControllerAdvice— the local always wins over the global.
- Exact exception type match wins over parent type —
CustomExceptionhandler beatsRuntimeExceptionhandler when aCustomExceptionis thrown.
Common Mistakes
Mistake 1 Expecting Custom Exception Fields to Automatically Appear in Response
1// ❌ Wrong assumption: throwing this will return 400 automatically2throw new CustomException(HttpStatus.BAD_REQUEST, "User ID is missing");3
4// But the response shows 500! Because no one reads the exception's fields.Fix: Either use @ExceptionHandler to read the fields and build a ResponseEntity, or annotate the exception class with @ResponseStatus.
Mistake 2 Using `response.sendError()` With `@ResponseStatus` on the Same Handler
1// ❌ Causes 500 — response is committed by sendError, then @ResponseStatus tries to commit again2@ResponseStatus(HttpStatus.BAD_REQUEST)3@ExceptionHandler(CustomException.class)4public void handle(CustomException e, HttpServletResponse res) throws IOException {5 res.sendError(403, "Forbidden"); // Commits response6 // @ResponseStatus tries to sendError again → exception → 5007}Fix: Use only one mechanism. Either return a ResponseEntity (and use @ResponseStatus to override it if needed), or use response.sendError() without @ResponseStatus on the method.
Mistake 3 Putting @ExceptionHandler in the Wrong Place
1// ❌ @ExceptionHandler in class A will NOT catch exceptions from class B2@ExceptionHandler(CustomException.class) // Only works inside UserController3public ResponseEntity<?> handle(CustomException e) { ... }Fix: Use @ControllerAdvice for global handling.
Mistake 4 Using Unsupported Parameter Types in @ExceptionHandler
1// ❌ String is not a supported parameter type — handler may not be invoked2@ExceptionHandler(CustomException.class)3public ResponseEntity<?> handle(CustomException e, String someString) { ... }Fix: Only use Exception (or subclass), HttpServletRequest, HttpServletResponse as parameters.
Mistake 5 Assuming `@ResponseStatus` on Exception Class Works When @ExceptionHandler Exists
1// ❌ Wrong assumption: both will work2@ResponseStatus(HttpStatus.BAD_REQUEST) // This will NOT be used by Resolver 2...3public class CustomException extends RuntimeException { ... }4
5// ...because Resolver 1 handles it via @ExceptionHandler first6@ExceptionHandler(CustomException.class)7public ResponseEntity<?> handle(CustomException e) { ... }Fix: Understand that once Resolver 1 handles an exception, Resolver 2 is never reached. @ResponseStatus on the exception class is meaningless when an @ExceptionHandler exists for that exception.
Best Practices
- Use
@ControllerAdvicewith@ExceptionHandleras the primary pattern — it is the industry standard, provides full control, and eliminates duplication across controllers.
- Always return
ResponseEntityfrom@ExceptionHandlermethods — it gives you explicit control over status code and response body without relying onDefaultErrorAttributes.
- Create a standardized
ErrorResponsePOJO — includetimestamp,status,message, and optionallypath. Consistency across all error responses makes client-side error handling easier.
- Add a catch-all handler in
@ControllerAdviceforException.class— ensures that even unexpected exceptions produce a structured JSON response instead of a raw 500 from the framework.
- Do not mix
@ResponseStatusand@ExceptionHandleron the same method — it causes confusion and potential 500 errors ifresponse.sendError()is involved.
- Use
@ResponseStatuson exception classes only for simple cases — it is clean and concise but gives less control over the response body than@ExceptionHandler.
- Keep controller-level
@ExceptionHandlermethods only for truly controller-specific handling — prefer@ControllerAdvicefor consistency.
- Log exceptions in your global handler — the
@ControllerAdviceclass is the ideal place to centralize exception logging, alerting, and monitoring.
Interview Notes
Q1: What are the five classes involved in Spring Boot exception handling?
Answer:
HandlerExceptionResolver— interface defining the contractHandlerExceptionResolverComposite— orchestrates the three resolvers in sequenceExceptionHandlerExceptionResolver— handles@ExceptionHandlerand@ControllerAdviceResponseStatusExceptionResolver— handles uncaught exceptions with@ResponseStatuson the classDefaultErrorAttributes— builds the final error response (timestamp, status, message, path)
Q2: In what sequence are the resolvers invoked?
Answer: ExceptionHandlerExceptionResolver → ResponseStatusExceptionResolver → DefaultHandlerExceptionResolver. They are invoked by HandlerExceptionResolverComposite. Once any resolver handles the exception, the remaining resolvers are skipped.
Q3: Why does throwing a custom exception with `HttpStatus.BAD_REQUEST` still return 500?
Answer: The HttpStatus field inside the custom exception is just a Java object field — the framework has no idea it exists. When no resolver handles the exception, DefaultErrorAttributes uses the default status of 500. To properly propagate the status, you must either: (a) use @ExceptionHandler to read the field and return a ResponseEntity, or (b) annotate the exception class with @ResponseStatus.
Q4: What is the difference between controller-level and global exception handling?
Answer: Controller-level @ExceptionHandler methods only handle exceptions thrown within that specific controller. Global exception handling uses a class annotated with @ControllerAdvice, where @ExceptionHandler methods apply to all controllers in the application. Controller-level handlers take priority over global ones for the same exception type.
Q5: What does `ResponseStatusExceptionResolver` handle?
Answer: It handles uncaught exceptions — exceptions not handled by ExceptionHandlerExceptionResolver (Resolver 1) — whose class is annotated with @ResponseStatus. The annotation must be on the exception class, not on a handler method. It reads the value (HTTP status) and reason (message) from the annotation and sets them in the response.
Q6: What happens if you use both `@ResponseStatus` and `@ExceptionHandler` on the same method with `response.sendError()`?
Answer: This causes a 500 Internal Server Error. response.sendError() commits the HTTP response immediately. When Spring Framework then tries to apply @ResponseStatus (by calling sendError again), the already-committed response cannot be written to, causing an exception inside the resolver itself, which results in 500.
Q7: Which takes priority `@ResponseStatus` or the `ResponseEntity` returned from an `@ExceptionHandler` method?
Answer: @ResponseStatus always wins when both are present on the same method. After the @ExceptionHandler method executes and returns a ResponseEntity, Spring Framework's ServletInvocableHandlerMethod detects @ResponseStatus on the method and overrides the status and message. This is handled by the framework, not by ResponseStatusExceptionResolver.
Q8: What does `DefaultHandlerExceptionResolver` handle?
Answer: It handles Spring Framework's own built-in exceptions — such as NoResourceFoundException (404), HttpRequestMethodNotSupportedException (405), HttpMediaTypeNotSupportedException (415), MissingServletRequestParameterException (400), and MethodArgumentNotValidException (400). It does not handle application-level custom exceptions.
Q9: If two `@ExceptionHandler` methods can both handle an exception one for `CustomException` and one for `RuntimeException` which is invoked?
Answer: The exact type match takes priority. If CustomException extends RuntimeException and both handlers exist, the CustomException handler is invoked. If no exact match exists, the resolver walks up the class hierarchy to find the closest matching handler.
Summary
| Concept | Key Point |
|---|---|
| 5 classes | HandlerExceptionResolver (interface), Composite (orchestrator), 3 Resolvers, DefaultErrorAttributes (builder) |
| Resolver sequence | ExceptionHandler → ResponseStatus → DefaultHandler |
| Default status | 500 — used when no resolver handles the exception |
| DefaultErrorAttributes | Always runs last; builds the JSON error response |
| Returning ResponseEntity | Bypasses DefaultErrorAttributes; you have full control |
| Resolver 1 | Handles @ExceptionHandler and @ControllerAdvice |
| Resolver 2 | Handles uncaught exceptions with @ResponseStatus on the exception class |
| Resolver 3 | Handles Spring framework built-in exceptions (404, 405, 415, etc.) |
@ControllerAdvice | Global exception handler — applies to all controllers |
| Controller vs Global priority | Controller-level handler wins over @ControllerAdvice |
| Exact vs Parent type | Exact exception type match wins over parent type match |
@ResponseStatus on method | Processed by Spring Framework, not Resolver 2; overrides ResponseEntity |
response.sendError() + @ResponseStatus | Causes 500 — committed response cannot be written again |
| Supported handler parameters | Exception (or subclass), HttpServletRequest, HttpServletResponse — any order |
@ControllerAdvice class with @ExceptionHandler methods returning ResponseEntity. No response.sendError(). No @ResponseStatus on handler methods. Clean, explicit, predictable.End of Study Guide — Spring Boot Exception Handling
Mastery check
How well can you recall this?
Finished this lesson?