wasAsked.

What is the correct way to implement consistent exception handling and Problem Details in Spring Boot?

Razorpay · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Boot, Software Engineering

Community answers

Posted by wasAsked editorial collection

Goal: every error becomes a consistent, machine-readable response with the right status code, no sensitive details, and a trace ID for support. 1. Use Problem Details (RFC 9457, which replaced RFC 7807) Spring Framework 6 provides ProblemDetail and ErrorResponse. Enable defaults for Spring MVC's own exceptions: spring.mvc.problemdetails.enabled=true 2. Centralise handling in a @RestControllerAdvice @RestControllerAdvice public class ApiExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(OrderNotFoundException.class) ProblemDetail handleNotFound(OrderNotFoundException ex) { ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage()); pd.setType(URI.create("https://api.example.com/problems/order-not-found")); pd.setTitle("Order not found"); return pd; } @ExceptionHandler(BusinessRuleException.class) ProblemDetail handleRule(BusinessRuleException ex) { ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.UNPROCESSABLE_ENTITY); pd.setTitle("Business rule violated"); pd.setProperty("code", ex.code()); return pd; } @ExceptionHandler(Exception.class) ProblemDetail handleUnexpected(Exception ex) { log.error("Unhandled exception", ex); return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred."); } } Extending ResponseEntityExceptionHandler gives consistent Problem Details for framework exceptions (method not allowed, unsupported media type, validation errors via MethodArgumentNotValidException); override handleMethodArgumentNotValid to add a field-error map. 3. Add tracing context Add a traceId property (from Micrometer Tracing's current span) to every ProblemDetail, for example in a common helper or a ResponseBodyAdvice, so users can quote it and support can find logs. 4. Rules - Correct status codes: 400 validation, 401 and 403 security, 404 not found, 409 conflicts (including optimistic locking), 422 business rules, 429 rate limits, 503 unavailable dependencies. - Stable type URIs or error codes the frontend can rely on; human-readable title and detail. - Never return stack traces, SQL messages or internal class names in production (server.error.include-stacktrace=never, include-message carefully). - Log unexpected exceptions once, with context; do not log expected client errors as ERROR. - Spring Security's 401 and 403 responses are produced by filters before controllers, so configure AuthenticationEntryPoint and AccessDeniedHandler to return Problem Details too. - Prefer specific domain exceptions (or exceptions implementing ErrorResponse) rather than generic RuntimeException. 5. Test it MockMvc tests asserting status, Content-Type application/problem+json, and fields for each error category, including security errors.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics