Video in progress
How do you use ProblemDetail to return all API errors in the same format?
Spring 6.1+ supports the RFC 9457 format (6.0 followed RFC 7807). spring.mvc.problemdetails.enabled=true switches the standard errors to it, and for your own exceptions you return a ProblemDetail from a @RestControllerAdvice or extend ErrorResponseException.
📖 Answer
The format:
{
"type": "https://shop.uz/errors/insufficient-funds",
"title": "Mablag' yetarli emas",
"status": 409,
"detail": "Hisobda 12 000 so'm bor, 50 000 kerak",
"instance": "/api/orders/77/pay",
"balance": 12000
}
Setup:
spring:
mvc:
problemdetails:
enabled: true
@RestControllerAdvice
class Errors extends ResponseEntityExceptionHandler { // Spring's own errors use this format too
@ExceptionHandler(InsufficientFunds.class)
ProblemDetail funds(InsufficientFunds e) {
ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
p.setType(URI.create("https://shop.uz/errors/insufficient-funds"));
p.setTitle("Mablag' yetarli emas");
p.setProperty("balance", e.balance());
return p;
}
}
The frontend and the mobile app write one parser and tell errors apart by type. Just don't put internals (SQL, stack traces) into detail.
Sign up to mark studied questions and save your progress.