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 + anerrorsfieldβ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)