@RestControllerAdvice and @ExceptionHandler
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ProductController answers a missing product nicely, but CategoryController throws the same exception and still gets a 500. Copying a handler into every controller brings the mess back. Where should the mapping live?
@ExceptionHandler inside one controller
@ExceptionHandler(SomeException.class) marks a method that Spring calls when a controller throws that exception type. The method's return value, such as a ResponseEntity, becomes the HTTP response instead of the default 500.
A handler inside ProductController turns ResourceNotFoundException into a 404 whose body is a small ApiError record.
Example 1 · ApiError.java and a handler inside ProductController
Runs in: the errors-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/common/ApiError.javapackage com.shoplite.lab.common;
/** Temporary error body for this lab. The ProblemDetail lesson replaces it with the standard one. */public record ApiError(int status, String title, String detail, String instance) {}
// src/main/java/com/shoplite/lab/product/ProductController.javapackage com.shoplite.lab.product;
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.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestController;
import com.shoplite.lab.common.ApiError;import com.shoplite.lab.common.ResourceNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) { this.productService = productService; }
@GetMapping("/{id}") public ProductResponse getProduct(@PathVariable long id) { return productService.findById(id); }
@GetMapping("/average-price") public AveragePriceResponse averagePrice(@RequestParam long categoryId) { return new AveragePriceResponse(categoryId, productService.averagePrice(categoryId)); }
@PostMapping @ResponseStatus(HttpStatus.CREATED) public ProductResponse create(@RequestBody CreateProductRequest request) { return productService.create(request); }
// Handles ResourceNotFoundException thrown by THIS controller only @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ApiError> handleNotFound(ResourceNotFoundException ex, HttpServletRequest request) { ApiError body = new ApiError(404, "Resource not found", ex.getMessage(), request.getRequestURI()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body); }}$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:15:41 GMT
{"status":404,"title":"Resource not found","detail":"Product 99 was not found.","instance":"/api/v1/products/99"}
$ curl -i http://localhost:8080/api/v1/categories/99
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:15:41 GMT
Connection: close
{"timestamp":"2026-10-16T05:15:41.474Z","status":500,"error":"Internal Server Error","path":"/api/v1/categories/99"}What this code does
handleNotFoundturnsResourceNotFoundExceptioninto a 404 whose body finally saysProduct 99 was not found.;request.getRequestURI()fillsinstance.CategoryControllerthrows the same exception, but this handler belongs toProductControlleronly, so the category request still gets the default 500.
Spring passes the handler the exception and, if the method asks for them, objects such as the HttpServletRequest. Placed inside a controller class, a handler covers only that controller, and copying it into every controller brings back the mess of the first lesson.
ApiError(status, title, detail, instance) is a temporary shape for this lab; the ProblemDetail lesson swaps it for the standard one with the same field names.
@RestControllerAdvice: one global handler
@RestControllerAdvice marks a class whose @ExceptionHandler methods apply to every controller in the app. It is @ControllerAdvice plus @ResponseBody, so return values are written as JSON.
The same handler moved into one GlobalExceptionHandler class, with a method for each ShopLite exception.
Example 2 · src/main/java/com/shoplite/lab/common/GlobalExceptionHandler.java
Runs in: the errors-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.common;
import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;
import jakarta.servlet.http.HttpServletRequest;
@RestControllerAdvicepublic class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ApiError> handleNotFound(ResourceNotFoundException ex, HttpServletRequest request) { return error(HttpStatus.NOT_FOUND, "Resource not found", ex.getMessage(), request); }
@ExceptionHandler(AlreadyExistsException.class) public ResponseEntity<ApiError> handleAlreadyExists(AlreadyExistsException ex, HttpServletRequest request) { return error(HttpStatus.CONFLICT, "Resource already exists", ex.getMessage(), request); }
@ExceptionHandler(ConflictException.class) public ResponseEntity<ApiError> handleConflict(ConflictException ex, HttpServletRequest request) { return error(HttpStatus.CONFLICT, "Conflict", ex.getMessage(), request); }
@ExceptionHandler(BusinessRuleException.class) public ResponseEntity<ApiError> handleBusinessRule(BusinessRuleException ex, HttpServletRequest request) { return error(HttpStatus.UNPROCESSABLE_CONTENT, "Business rule broken", ex.getMessage(), request); }
private ResponseEntity<ApiError> error(HttpStatus status, String title, String detail, HttpServletRequest request) { ApiError body = new ApiError(status.value(), title, detail, request.getRequestURI()); return ResponseEntity.status(status).body(body); }}$ curl http://localhost:8080/api/v1/products/99
{"status":404,"title":"Resource not found","detail":"Product 99 was not found.","instance":"/api/v1/products/99"}
$ curl http://localhost:8080/api/v1/categories/99
{"status":404,"title":"Resource not found","detail":"Category 99 was not found.","instance":"/api/v1/categories/99"}
$ curl -X POST http://localhost:8080/api/v1/orders/99/cancel
{"status":404,"title":"Resource not found","detail":"Order 99 was not found.","instance":"/api/v1/orders/99/cancel"}
$ curl -X POST http://localhost:8080/api/v1/orders/14/cancel
{"status":409,"title":"Conflict","detail":"Order 14 is SHIPPED and can no longer be cancelled.","instance":"/api/v1/orders/14/cancel"}What this code does
- The local handler is gone from
ProductController. Products, categories and orders now all get the same 404 body from one class. ConflictExceptionandAlreadyExistsExceptioneach have a handler. Cancelling shipped order 14 throwsInvalidStateException, which has none, so theConflictExceptionhandler answers with the titleConflict.- The private
errorhelper builds every reply, so status, title and path are filled the same way each time.
The mapping from exception type to status and title now lives in one class. Services throw meaningful exceptions, controllers stay one line long, and GlobalExceptionHandler decides the reply, so a new endpoint gets correct errors without a line of error code.
Spring finds the advice class by component scanning, like a controller, so keep it inside the main application's package, here com.shoplite.lab.common.
Order of execution
Follow one failing request
Put the steps in the order they happen when product 99 is requested.
Which handler wins: the most specific exception type
The most specific match is the rule Spring uses to pick one @ExceptionHandler: start at the thrown exception's class, walk up its parents, and the first type that has a handler wins. The order of the methods in the file does not matter.
A small model of Spring's rule, run on four ShopLite exceptions.
Example 3 · How Spring picks a handler: closest parent first
import java.util.LinkedHashMap;import java.util.Map;
abstract class ShopLiteException extends RuntimeException { protected ShopLiteException(String message) { super(message); }}
class ResourceNotFoundException extends ShopLiteException { ResourceNotFoundException(String message) { super(message); }}
abstract class ConflictException extends ShopLiteException { protected ConflictException(String message) { super(message); }}
class AlreadyExistsException extends ConflictException { AlreadyExistsException(String message) { super(message); }}
class InvalidStateException extends ConflictException { InvalidStateException(String message) { super(message); }}
public class HandlerChoiceDemo { // The exception types our advice has handlers for, like the @ExceptionHandler methods static final Map<Class<?>, String> HANDLERS = new LinkedHashMap<>();
static { HANDLERS.put(Exception.class, "handleUnexpected -> 500"); HANDLERS.put(ConflictException.class, "handleConflict -> 409 Conflict"); HANDLERS.put(AlreadyExistsException.class, "handleAlreadyExists -> 409 Resource already exists"); HANDLERS.put(ResourceNotFoundException.class, "handleNotFound -> 404"); }
// Spring's rule: start at the thrown class and walk up to its parents; the first match wins static String pick(Class<?> thrown) { int steps = 0; for (Class<?> type = thrown; type != null; type = type.getSuperclass(), steps++) { if (HANDLERS.containsKey(type)) { return HANDLERS.get(type) + " (" + steps + " step" + (steps == 1 ? "" : "s") + " up)"; } } return "no handler"; }
public static void main(String[] args) { Class<?>[] thrown = { AlreadyExistsException.class, InvalidStateException.class, ResourceNotFoundException.class, ArithmeticException.class }; for (Class<?> type : thrown) { System.out.println(type.getSimpleName() + ": " + pick(type)); } }}AlreadyExistsException: handleAlreadyExists -> 409 Resource already exists (0 steps up) InvalidStateException: handleConflict -> 409 Conflict (1 step up) ResourceNotFoundException: handleNotFound -> 404 (0 steps up) ArithmeticException: handleUnexpected -> 500 (2 steps up)
What this code does
pickcopies Spring's rule: begin at the thrown class and followgetSuperclass()until a type with a handler appears. It is a model of the rule, not Spring's own code.AlreadyExistsExceptionmatches its own handler at 0 steps;InvalidStateExceptionreachesConflictExceptionafter 1 step;ArithmeticExceptiononly reachesException.- The
Exceptionhandler was registered first, yet it wins only forArithmeticException: order in the class does not matter, distance does.
Write one general handler for a whole family of exceptions, and a specific one only for the cases that need a different title or extra data.
A catch-all handler that logs and returns a safe 500
A catch-all handler is @ExceptionHandler(Exception.class): the method that receives every exception no other handler matched. It logs the full stack trace and returns a 500 with a fixed, harmless sentence.
A first catch-all that logs the request and answers with a fixed sentence, then what it does to Spring's own errors.
Example 4 · A first catch-all, and the trap it falls into
Runs in: the errors-lab practice project (Spring Boot 4.1)
// in GlobalExceptionHandler (first try)private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)public ResponseEntity<ApiError> handleUnexpected(Exception ex, HttpServletRequest request) { log.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex); return error(HttpStatus.INTERNAL_SERVER_ERROR, "Internal server error", "Something went wrong on our side. Please try again later.", request);}$ curl -i "http://localhost:8080/api/v1/products/average-price?categoryId=7"
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:12 GMT
Connection: close
{"status":500,"title":"Internal server error","detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products/average-price"}
$ curl -i http://localhost:8080/api/v1/prodcts
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:12 GMT
Connection: close
{"status":500,"title":"Internal server error","detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/prodcts"}
$ curl -i -X DELETE http://localhost:8080/api/v1/orders/14/cancel
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:13 GMT
Connection: close
{"status":500,"title":"Internal server error","detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/orders/14/cancel"}
Server console (first request):
2026-10-16T10:44:13.094+05:30 ERROR 20984 --- [nio-8080-exec-9] c.s.lab.common.GlobalExceptionHandler : Unexpected error on GET /api/v1/products/average-price
java.lang.ArithmeticException: / by zero
at java.base/java.math.BigDecimal.divideAndRound(BigDecimal.java:4955) ~[na:na]
at java.base/java.math.BigDecimal.divide(BigDecimal.java:6028) ~[na:na]
at java.base/java.math.BigDecimal.divide(BigDecimal.java:1653) ~[na:na]
at java.base/java.math.BigDecimal.divide(BigDecimal.java:1683) ~[na:na]
at com.shoplite.lab.product.ProductService.averagePrice(ProductService.java:57) ~[!/:0.0.1-SNAPSHOT]
at com.shoplite.lab.product.ProductController.averagePrice(ProductController.java:30) ~[!/:0.0.1-SNAPSHOT]
...What this code does
- The real bug (a division by zero for category 7, which has no products) now gets a safe 500 body, and the log has the request and the full stack trace pointing at
ProductService.java:57. - But a typo URL and a wrong method also became 500, lost their
Allowheader and were logged as bugs. The catch-all caught Spring MVC's ownNoResourceFoundExceptionandHttpRequestMethodNotSupportedException.
Example 5 · The catch-all that keeps Spring's own 4xx answers
Runs in: the errors-lab practice project (Spring Boot 4.1)
// in GlobalExceptionHandler@ExceptionHandler(Exception.class)public ResponseEntity<ApiError> handleUnexpected(Exception ex, HttpServletRequest request) { if (ex instanceof ErrorResponse springError) { // Spring MVC's own errors (unknown URL, wrong method...) keep their 4xx status HttpStatusCode status = springError.getStatusCode(); return ResponseEntity.status(status) .headers(springError.getHeaders()) .body(new ApiError(status.value(), springError.getBody().getTitle(), springError.getBody().getDetail(), request.getRequestURI())); } log.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex); return error(HttpStatus.INTERNAL_SERVER_ERROR, "Internal server error", "Something went wrong on our side. Please try again later.", request);}$ curl -i http://localhost:8080/api/v1/prodcts
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:14:13 GMT
{"status":404,"title":"Not Found","detail":"No static resource api/v1/prodcts.","instance":"/api/v1/prodcts"}
$ curl -i -X DELETE http://localhost:8080/api/v1/orders/14/cancel
HTTP/1.1 405
Allow: POST
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:14:13 GMT
{"status":405,"title":"Method Not Allowed","detail":"Method 'DELETE' is not supported.","instance":"/api/v1/orders/14/cancel"}
$ curl -i http://localhost:8080/api/v1/products/abc
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:14:14 GMT
Connection: close
{"status":500,"title":"Internal server error","detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products/abc"}What this code does
ErrorResponseexceptions carry their own status, headers and a short title and detail, so the typo URL is 404 again and the wrong method is 405 withAllow: POST. They are not logged as bugs./products/abcis still 500:MethodArgumentTypeMismatchExceptionis not anErrorResponse. The next lesson gives bad input its own handlers, and the ProblemDetail lesson replaces thisinstanceofwith a cleaner base class.
The catch-all receives real bugs, such as a NullPointerException, a division by zero or a lost database connection. The client must never see the exception message, because text like / by zero or a SQL error describes your code. The developer sees everything, because the log gets the request and the whole stack trace.
There is a trap. Spring MVC reports its own errors, such as an unknown URL (404) or a wrong method (405), as exceptions too, and a catch-all turns them into 500. Those exceptions implement Spring's ErrorResponse interface, which knows the right status; the second example uses it.
Never swallow: log with the stack trace once, in one place
Swallowing an exception means catching it and carrying on as if nothing happened: an empty catch, a return null or a default value. The request then "succeeds" with wrong data and nothing reaches the log.
Three bad ways to handle a failure, and the one right way.
// 1. Swallowed: wrong answer, no trace anywherecatch (Exception e) { return BigDecimal.ZERO; }
// 2. Message only: the log says "/ by zero" but not wherelog.error("Failed: " + e.getMessage());
// 3. Logged twice: here and again in the global handlercatch (ArithmeticException e) { log.error("Average failed", e); throw e; }
// Right: let it fly; GlobalExceptionHandler logs it oncelog.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex);- Pass the exception as the last argument of
log.error(...); SLF4J then prints the full stack trace. - Log a bug in one place, the catch-all handler, so each failure gives one stack trace, not two or three.
- Expected errors (404, 409, 422) need no stack trace; they are normal answers, not bugs.
Example 6 · Swallowed: a wrong answer with status 200
Runs in: the errors-lab practice project (Spring Boot 4.1)
// in ProductService (bad version)public BigDecimal averagePrice(long categoryId) { List<BigDecimal> prices = products.values().stream() .filter(p -> p.categoryId() == categoryId) .map(ProductResponse::price) .toList(); BigDecimal total = prices.stream().reduce(BigDecimal.ZERO, BigDecimal::add); try { return total.divide(BigDecimal.valueOf(prices.size()), 2, RoundingMode.HALF_UP); } catch (Exception e) { return BigDecimal.ZERO; // swallowed: no log, no error, a wrong answer }}$ curl -i "http://localhost:8080/api/v1/products/average-price?categoryId=7"
HTTP/1.1 200
Content-Type: application/json
Content-Length: 33
Date: Fri, 16 Oct 2026 05:16:41 GMT
{"categoryId":7,"averagePrice":0}
Server console: (nothing)What this code does
- The
catchhides the division by zero and returns 0, so the client is told that Home & Kitchen items cost Rs 0 on average, with status 200. - The log is empty. Nobody learns that the method has a bug until a customer complains. Removing the
try/catchgives the honest 500 and one logged stack trace from Example 4.
Find the bug
Spot the bad handling
Click the line that hides or duplicates the error.
Which line swallows the exception?
Round 1 of 3Next step
Check your understanding
12 quick questions