close

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):

  • MethodArgumentNotValidException β†’ 400 + an errors fieldβ†’message map
  • OrderNotFoundException β†’ 404
  • IllegalStateException (confirming an already-confirmed order) β†’ 409 Conflict
  • any other Exception β†’ 500 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)