Global Exception Handling
global exception handling a @controlleradvice class centralises exception-to-http-response mapping across all controllers. no more try/catch in every endpoint — one place handles
Introduction
A @ControllerAdvice class centralises exception-to-HTTP-response mapping across all controllers. No more try/catch in every endpoint — one place handles validation errors, not-found, auth failures and unexpected exceptions.
Informative example
Centralised error responses:
@RestControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(ResourceNotFoundException.class)ResponseEntity<ErrorResponse> notFound(ResourceNotFoundException ex) {return ResponseEntity.status(404).body(new ErrorResponse("NOT_FOUND", ex.getMessage()));}@ExceptionHandler(MethodArgumentNotValidException.class)ResponseEntity<ErrorResponse> validation(MethodArgumentNotValidException ex) {var errors = ex.getBindingResult().getFieldErrors().stream().collect(toMap(FieldError::getField, FieldError::getDefaultMessage));return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_FAILED", errors));}@ExceptionHandler(Exception.class)ResponseEntity<ErrorResponse> fallback(Exception ex) {log.error("Unhandled", ex);return ResponseEntity.status(500).body(new ErrorResponse("INTERNAL_ERROR", "Something went wrong"));}}
Best practices
- Never expose stack traces to clients in production.
- Use consistent error response shape: code, message, details, timestamp.
- Log the full exception server-side; return safe message client-side.
Purpose of this lesson
Master Global Exception Handling so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Global Exception Handling.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when global exception handling is the right tool for the problem.
Useful template
RFC 7807 ProblemDetail
@ExceptionHandler(ResourceNotFoundException.class)ProblemDetail notFound(ResourceNotFoundException ex) {return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage());}
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Global Exception Handling daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Global Exception Handling in one minute.
Q2When would you avoid Global Exception Handling?
Summary
In this lesson you learned Global Exception Handling — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.