DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

OrderHub Day 5: Clean Error Handling With RFC-7807 ProblemDetail (Spring Boot)

OrderHub Day 5: stop returning ugly, inconsistent errors. Today every failure — validation, not-found, bad state, or an unexpected crash — comes back in ONE standard, machine-readable shape: RFC-7807 ProblemDetail. One @RestControllerAdvice does it all.

🚧 See every error shape: https://dev48v.infy.uk/orderhub/day5-exception-handling.html

The problem with scattered try/catch

Handle errors in each controller and you get inconsistent JSON, leaked stack traces, and duplicated code. Centralize it instead.

One advice, RFC-7807 everywhere

Spring Boot 3 has ProblemDetail built in. A single @RestControllerAdvice maps exceptions to a consistent envelope (type, title, status, detail, instance, + extensions):

  • MethodArgumentNotValidException400 + an errors field→message map
  • OrderNotFoundException404
  • IllegalStateException (confirming an already-confirmed order) → 409 Conflict
  • any other Exception500 with a generic message — never leak the stack trace

Let exceptions flow

The trick: don't swallow errors in controllers. The service throws a domain exception (OrderNotFoundException), it propagates up, and the advice turns it into the right status. Controllers stay clean; the web layer owns HTTP, the service owns domain rules.

🔨 Full walkthrough (@RestControllerAdvice → ProblemDetail → 400/404/409/500, no leaks) on the page: https://dev48v.infy.uk/orderhub/day5-exception-handling.html

OrderHub — a production-grade Spring Boot backend, one feature a day.
🌐 https://dev48v.infy.uk · Code: https://github.com/dev48v/order-hub-from-zero

Top comments (0)