Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Spring
Springhard

How do you handle exceptions globally in Spring MVC?

Tags
#controlleradvice#exceptionhandler#error-handling
Back to categoryPractice quiz

Answer

Use `@ControllerAdvice` with `@ExceptionHandler` to map exceptions to consistent HTTP responses (status + body). It keeps controllers clean and centralizes error handling.

@ControllerAdvice
class ApiErrors {
  @ExceptionHandler(IllegalArgumentException.class)
  ResponseEntity<String> badRequest(IllegalArgumentException e) {
    return ResponseEntity.badRequest().body(e.getMessage());
  }
}

Advanced answer

Deep dive

Global exception handling in Spring MVC is commonly done with:

  • `@ControllerAdvice` (applies to MVC controllers)
  • `@RestControllerAdvice` (same, but handler return values are written to the response body by default)

You map exception types to HTTP responses using `@ExceptionHandler`. For rich responses, return `ResponseEntity<?>` (status, headers, body) or use `ProblemDetail` in newer Spring versions.

What to centralize

  • Consistent error shape (e.g., `errorCode`, `message`, `path`, `correlationId`).
  • Validation errors (`MethodArgumentNotValidException`) → field-level messages.
  • Logging + mapping internal exceptions to safe public messages.

Example

@RestControllerAdvice
class ApiErrors {
  @ExceptionHandler(IllegalArgumentException.class)
  ResponseEntity<ProblemDetail> badRequest(IllegalArgumentException e) {
    var pd = ProblemDetail.forStatus(400);
    pd.setTitle("Bad request");
    pd.setDetail(e.getMessage());
    return ResponseEntity.badRequest().body(pd);
  }
}

Common pitfalls

  • Leaking stack traces or internal messages to clients.
  • Returning different error shapes per controller.

Related questions

Java
Checked vs Unchecked Exceptions?
#exception#error-handling#java
  • Treating everything as 500 instead of meaningful statuses (400/404/409).