Skip to the page

Spring REST APIs · core

Error handling with @RestControllerAdvice

A global handler maps exceptions to the right status and a safe body. Never return 200 for errors, and never leak internal messages.

The notes

What you must know

  • Return the real status. Always 200 makes clients, gateways, retries and monitoring think the call worked.
  • Do not return e.getMessage() or a stack trace: they leak SQL, table names and hosts. Log details on the server; send a generic message and a correlation id.
  • One catch-all handler hides differences: validation (400), not found (404), conflict (409) and real bugs (500) must look different. Map your own exceptions to statuses.
  • Log the exception, or failures vanish.
  • Extend ResponseEntityExceptionHandler so Spring's own errors (bad JSON, 405, 415, missing parameters) keep their proper status.
  • @RestControllerAdvice = @ControllerAdvice + @ResponseBody.
  • Errors as RFC 9457 Problem Details: spring.mvc.problemdetails.enabled=true (off by default) or return ProblemDetail from the advice.

The red pen

Common traps: mistake → fix

  • Mistake: Returning 200 with an error body is friendlier

    Fix: clients and monitoring treat it as success.

  • Mistake: Showing the exception message helps users

    Fix: it leaks internals.

  • Mistake: One Exception handler is enough

    Fix: it makes validation errors look like server errors.

Easy to hard

Questions interviewers ask, easy to hard

  1. Review this global handler for a payments API. What is wrong?
  2. How do you keep Spring's own 405 and 415 responses correct?
  3. What is Problem Details?
  4. Where do you log, and what do you send to the client?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview