ProblemDetail and RFC 9457 errors
55 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every team once invented its own error JSON, so every client needed its own parsing code. Which standard shape can the ShopLite API use so that any client already understands its errors?
The standard: type, title, status, detail and instance
RFC 9457 (Problem Details for HTTP APIs) is the standard JSON shape for API errors: type, title, status, detail and instance, sent with the content type application/problem+json.
Call a missing product and read the five standard fields in the reply.
curl -i http://localhost:8080/api/v1/products/99HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:27:48 GMT
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Product 99 was not found.","instance":"/api/v1/products/99"}typeis a URI that names the kind of problem, and clients branch on it;titleis a short fixed summary of that kind. Both stay the same for every problem of that kind.statusis the HTTP status code,detailis a sentence about this one occurrence andinstanceis the URI of the request that failed.- RFC 9457 (2023) replaced RFC 7807 (2016). The fields are the same; 9457 adds clearer rules and a shared registry of common types. Older articles say "RFC 7807".
- Fields beyond the five are allowed and are called extension members, such as
errorsfor validation.
type URI only has to be unique; it does not have to open a web page. ShopLite uses https://shoplite.example/problems/<kind> as its contract says.Spring's ProblemDetail class and application/problem+json
ProblemDetail is Spring's class for one problem body. ProblemDetail.forStatusAndDetail(status, detail) creates one, setType, setTitle and setInstance fill the rest, and Spring writes it as application/problem+json.
A small ProblemKind enum keeps the contract's table in one place, and each handler shrinks to one line.
Example 1 · ProblemKind.java and the ShopLite exception handlers
Runs in: the errors-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/common/ProblemKind.javapackage com.shoplite.lab.common;
import java.net.URI;
import org.springframework.http.HttpStatus;import org.springframework.http.ProblemDetail;
/** Every kind of error the API can return: one type URI, status and title each. */public enum ProblemKind {
VALIDATION_FAILED(HttpStatus.BAD_REQUEST, "validation-failed", "Validation failed"), MALFORMED_REQUEST(HttpStatus.BAD_REQUEST, "malformed-request", "Malformed request"), NOT_FOUND(HttpStatus.NOT_FOUND, "not-found", "Resource not found"), METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, "method-not-allowed", "Method not allowed"), UNSUPPORTED_MEDIA_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported-media-type", "Unsupported media type"), ALREADY_EXISTS(HttpStatus.CONFLICT, "already-exists", "Resource already exists"), IN_USE(HttpStatus.CONFLICT, "in-use", "Resource in use"), OUT_OF_STOCK(HttpStatus.CONFLICT, "out-of-stock", "Not enough stock"), INVALID_STATE(HttpStatus.CONFLICT, "invalid-state", "Invalid state change"), RULE_BROKEN(HttpStatus.UNPROCESSABLE_CONTENT, "rule-broken", "Business rule broken"), INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "internal-error", "Internal server error");
private static final String TYPE_BASE = "https://shoplite.example/problems/";
private final HttpStatus status; private final URI type; private final String title;
ProblemKind(HttpStatus status, String slug, String title) { this.status = status; this.type = URI.create(TYPE_BASE + slug); this.title = title; }
public HttpStatus status() { return status; }
public ProblemDetail problem(String detail) { ProblemDetail problem = ProblemDetail.forStatusAndDetail(status, detail); problem.setType(type); problem.setTitle(title); return problem; }}
// src/main/java/com/shoplite/lab/common/GlobalExceptionHandler.java (ShopLite exceptions)@ExceptionHandler(ResourceNotFoundException.class)public ProblemDetail handleNotFound(ResourceNotFoundException ex) { return ProblemKind.NOT_FOUND.problem(ex.getMessage());}
@ExceptionHandler(AlreadyExistsException.class)public ProblemDetail handleAlreadyExists(AlreadyExistsException ex) { return ProblemKind.ALREADY_EXISTS.problem(ex.getMessage());}
@ExceptionHandler(InvalidStateException.class)public ProblemDetail handleInvalidState(InvalidStateException ex) { return ProblemKind.INVALID_STATE.problem(ex.getMessage());}
@ExceptionHandler(BusinessRuleException.class)public ProblemDetail handleBusinessRule(BusinessRuleException ex) { return ProblemKind.RULE_BROKEN.problem(ex.getMessage());}$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"MOB-RN13","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"A product with SKU MOB-RN13 already exists.","instance":"/api/v1/products"}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":42,"price":999.00,"stock":30}'
{"type":"https://shoplite.example/problems/rule-broken","title":"Business rule broken","status":422,"detail":"Category 42 does not exist.","instance":"/api/v1/products"}
$ curl -X POST http://localhost:8080/api/v1/orders/14/cancel
{"type":"https://shoplite.example/problems/invalid-state","title":"Invalid state change","status":409,"detail":"Order 14 is SHIPPED and can no longer be cancelled.","instance":"/api/v1/orders/14/cancel"}What this code does
- Each enum constant holds one row of the contract's error table.
problem(detail)builds aProblemDetailwith that row's type, title and status. - The handlers return
ProblemDetaildirectly. Spring setsContent-Type: application/problem+jsonand fillsinstancewith the request path. - The detail comes from the exception message, which the previous lessons made safe and specific.
When a handler returns a ProblemDetail, Spring fills instance with the request path if you left it empty. The temporary ApiError record goes away, and a handler becomes one line: ProblemKind.NOT_FOUND.problem(ex.getMessage()).
Spring Boot 4 uses Jackson 3, which by default writes the properties of a class such as ProblemDetail in A to Z order (detail first). spring.jackson.mapper.sort-properties-alphabetically=false keeps the RFC order type, title, status, detail, instance. The order does not change the meaning, but it makes replies easier to read against the contract.
Extra properties: errors, timestamp and a trace id
An extension member is an extra field added to a problem body beyond the five standard ones, written with setProperty(name, value). ShopLite uses errors for validation and productId, available and requested for out of stock.
Out-of-stock and validation replies carry extra fields after the five standard ones.
Example 2 · Extension members: errors and the out-of-stock numbers
Runs in: the errors-lab practice project (Spring Boot 4.1)
// in GlobalExceptionHandler@ExceptionHandler(OutOfStockException.class)public ProblemDetail handleOutOfStock(OutOfStockException ex) { ProblemDetail problem = ProblemKind.OUT_OF_STOCK.problem(ex.getMessage()); problem.setProperty("productId", ex.getProductId()); problem.setProperty("available", ex.getAvailable()); problem.setProperty("requested", ex.getRequested()); return problem;}
private ResponseEntity<Object> validationFailed(List<InvalidField> errors, HttpHeaders headers) { long fields = errors.stream().map(InvalidField::field).distinct().count(); String detail = "The request has " + fields + (fields == 1 ? " invalid field." : " invalid fields."); ProblemDetail problem = ProblemKind.VALIDATION_FAILED.problem(detail); problem.setProperty("errors", errors); return respond(problem, headers);}$ curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":2,"addressId":3,"items":[{"productId":3,"quantity":9}]}'
{"type":"https://shoplite.example/problems/out-of-stock","title":"Not enough stock","status":409,"detail":"Only 8 units of iPhone 15 128GB are in stock; 9 were requested.","instance":"/api/v1/orders","productId":3,"available":8,"requested":9}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 3 invalid fields.","instance":"/api/v1/products","errors":[{"field":"sku","message":"must be 3-20 characters: A-Z, 0-9 or -"},{"field":"name","message":"must be 2-120 characters"},{"field":"price","message":"must be greater than 0"}]}What this code does
setPropertyadds fields after the standard five, exactly as the contract shows:productId,availableandrequestedlet the app say "only 8 left".errorsholds the sameInvalidFieldlist as in the last lesson; Jackson writes each record as{"field", "message"}.
Example 3 · A timestamp and a trace id in the 500 reply
Runs in: the errors-lab practice project (Spring Boot 4.1)
// in GlobalExceptionHandler (a variant: not part of the ShopLite v1 contract)@ExceptionHandler(Exception.class)public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) { String traceId = UUID.randomUUID().toString().substring(0, 8); log.error("Unexpected error [traceId={}] on {} {}", traceId, request.getMethod(), request.getRequestURI(), ex); ProblemDetail problem = ProblemKind.INTERNAL_ERROR.problem( "Something went wrong on our side. Quote trace id " + traceId + " to support."); problem.setProperty("timestamp", OffsetDateTime.now(ZoneId.of("Asia/Kolkata"))); problem.setProperty("traceId", traceId); return problem;}$ curl -i "http://localhost:8080/api/v1/products/average-price?categoryId=7"
HTTP/1.1 500
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:29:26 GMT
Connection: close
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Quote trace id db704626 to support.","instance":"/api/v1/products/average-price","timestamp":"2026-10-16T11:59:26.1390885+05:30","traceId":"db704626"}
Server console:
2026-10-16T11:59:26.127+05:30 ERROR 9792 --- [errors-lab] [nio-8080-exec-1] c.s.lab.common.GlobalExceptionHandler : Unexpected error [traceId=db704626] on GET /api/v1/products/average-price
java.lang.ArithmeticException: / by zero
at java.base/java.math.BigDecimal.divideAndRound(BigDecimal.java:4955) ~[na:na]
...What this code does
- The same
db704626appears in the reply and in the log line, so support can find this one stack trace among thousands. OffsetDateTimewithAsia/Kolkatais written as an ISO time with+05:30, like other ShopLite times. Your id and time will differ on every run.
Two common extras are a timestamp and a trace id: a short random code that the server writes both into the reply and into the log line. When a user reports "trace id db704626", you find the exact stack trace in seconds.
The ShopLite v1 contract lists only errors and the out-of-stock numbers, so the module project does not add timestamp or traceId. Clients must ignore fields they do not know, so adding them later breaks no one; the second example shows how it looks.
spring.mvc.problemdetails.enabled and ResponseEntityExceptionHandler
ResponseEntityExceptionHandler is a ready-made Spring base class whose methods handle each Spring MVC exception (unknown URL, wrong method, wrong type, unreadable body) and return a ProblemDetail. Extend it in your advice and override the cases you care about.
First spring.mvc.problemdetails.enabled=true on its own, then the full ShopLite advice extending the base class.
Example 4 · spring.mvc.problemdetails.enabled=true on its own
Runs in: the errors-lab project as it was in the Custom exceptions lesson, with spring.mvc.problemdetails.enabled=true
curl -i http://localhost:8080/api/v1/prodctscurl -i -X DELETE http://localhost:8080/api/v1/products/1curl -i http://localhost:8080/api/v1/products/abccurl -i http://localhost:8080/api/v1/products/99$ curl -i http://localhost:8080/api/v1/prodcts
HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:29:14 GMT
{"detail":"No static resource api/v1/prodcts.","instance":"/api/v1/prodcts","status":404,"title":"Not Found"}
$ curl -i -X DELETE http://localhost:8080/api/v1/products/1
HTTP/1.1 405
Allow: GET
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:29:14 GMT
{"detail":"Method 'DELETE' is not supported.","instance":"/api/v1/products/1","status":405,"title":"Method Not Allowed"}
$ curl -i http://localhost:8080/api/v1/products/abc
HTTP/1.1 400
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:29:14 GMT
Connection: close
{"detail":"Failed to convert 'id' with value: 'abc'","instance":"/api/v1/products/abc","status":400,"title":"Bad Request"}
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:29:15 GMT
Connection: close
{"timestamp":"2026-10-16T06:29:15.188Z","status":500,"error":"Internal Server Error","path":"/api/v1/products/99"}What this code does
- Spring MVC's own errors are now problem details, with Spring's titles and no
type. The fields come out A to Z because this project does not set the Jackson ordering property. - The last call shows the gap: the service's
ResourceNotFoundExceptionis not a Spring MVC exception, so it still gets the old 500 JSON body. One API, two formats.
Example 5 · src/main/java/com/shoplite/lab/common/GlobalExceptionHandler.java
Runs in: the errors-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.common;
import java.util.ArrayList;import java.util.List;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.TypeMismatchException;import org.springframework.context.MessageSourceResolvable;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatusCode;import org.springframework.http.ProblemDetail;import org.springframework.http.ResponseEntity;import org.springframework.http.converter.HttpMessageNotReadableException;import org.springframework.validation.method.ParameterErrors;import org.springframework.validation.method.ParameterValidationResult;import org.springframework.web.HttpMediaTypeNotSupportedException;import org.springframework.web.HttpRequestMethodNotSupportedException;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.MissingServletRequestParameterException;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import org.springframework.web.context.request.WebRequest;import org.springframework.web.method.annotation.HandlerMethodValidationException;import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;import org.springframework.web.servlet.resource.NoResourceFoundException;
import jakarta.servlet.http.HttpServletRequest;import tools.jackson.core.JacksonException;import tools.jackson.databind.exc.MismatchedInputException;import tools.jackson.databind.exc.UnrecognizedPropertyException;
@RestControllerAdvicepublic class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
// ---- Spring MVC's own exceptions: override the base class methods ----
@Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { Object target = ex.getBindingResult().getTarget(); return validationFailed(InvalidFields.of(ex.getBindingResult(), target), headers); }
@Override protected ResponseEntity<Object> handleHandlerMethodValidationException(HandlerMethodValidationException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { List<InvalidField> errors = new ArrayList<>(); for (ParameterValidationResult result : ex.getParameterValidationResults()) { if (result instanceof ParameterErrors bodyErrors) { errors.addAll(InvalidFields.of(bodyErrors, bodyErrors.getArgument())); } else { String name = result.getMethodParameter().getParameterName(); for (MessageSourceResolvable error : result.getResolvableErrors()) { errors.add(new InvalidField(name, error.getDefaultMessage())); } } } return validationFailed(errors, headers); }
@Override protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { Class<?> type = ex.getRequiredType(); boolean number = type != null && (Number.class.isAssignableFrom(type) || type == int.class || type == long.class || type == double.class); String message = number ? "must be a number" : "has an invalid value"; return validationFailed(List.of(new InvalidField(ex.getPropertyName(), message)), headers); }
@Override protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return validationFailed(List.of(new InvalidField(ex.getParameterName(), "is required")), headers); }
@Override protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return respond(ProblemKind.MALFORMED_REQUEST.problem(describe(ex)), headers); }
@Override protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { String detail = ex.getMethod() + " is not supported on this URL."; return respond(ProblemKind.METHOD_NOT_ALLOWED.problem(detail), headers); }
@Override protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { String detail = "Content-Type " + ex.getContentType() + " is not supported. Send application/json."; return respond(ProblemKind.UNSUPPORTED_MEDIA_TYPE.problem(detail), headers); }
@Override protected ResponseEntity<Object> handleNoResourceFoundException(NoResourceFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { String detail = "There is no endpoint " + ex.getHttpMethod() + " /" + ex.getResourcePath() + "."; return respond(ProblemKind.NOT_FOUND.problem(detail), headers); }
// ---- ShopLite exceptions ----
@ExceptionHandler(ResourceNotFoundException.class) public ProblemDetail handleNotFound(ResourceNotFoundException ex) { return ProblemKind.NOT_FOUND.problem(ex.getMessage()); }
@ExceptionHandler(AlreadyExistsException.class) public ProblemDetail handleAlreadyExists(AlreadyExistsException ex) { return ProblemKind.ALREADY_EXISTS.problem(ex.getMessage()); }
@ExceptionHandler(OutOfStockException.class) public ProblemDetail handleOutOfStock(OutOfStockException ex) { ProblemDetail problem = ProblemKind.OUT_OF_STOCK.problem(ex.getMessage()); problem.setProperty("productId", ex.getProductId()); problem.setProperty("available", ex.getAvailable()); problem.setProperty("requested", ex.getRequested()); return problem; }
@ExceptionHandler(InvalidStateException.class) public ProblemDetail handleInvalidState(InvalidStateException ex) { return ProblemKind.INVALID_STATE.problem(ex.getMessage()); }
@ExceptionHandler(BusinessRuleException.class) public ProblemDetail handleBusinessRule(BusinessRuleException ex) { return ProblemKind.RULE_BROKEN.problem(ex.getMessage()); }
// ---- anything else: log once with the stack trace, answer with a safe 500 ----
@ExceptionHandler(Exception.class) public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) { log.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex); return ProblemKind.INTERNAL_ERROR.problem("Something went wrong on our side. Please try again later."); }
private ResponseEntity<Object> validationFailed(List<InvalidField> errors, HttpHeaders headers) { long fields = errors.stream().map(InvalidField::field).distinct().count(); String detail = "The request has " + fields + (fields == 1 ? " invalid field." : " invalid fields."); ProblemDetail problem = ProblemKind.VALIDATION_FAILED.problem(detail); problem.setProperty("errors", errors); return respond(problem, headers); }
private ResponseEntity<Object> respond(ProblemDetail problem, HttpHeaders headers) { return ResponseEntity.status(problem.getStatus()).headers(headers).body(problem); }
private static String describe(HttpMessageNotReadableException ex) { Throwable cause = ex.getCause(); if (cause instanceof UnrecognizedPropertyException unknown) { return "Unknown field " + path(unknown) + "."; } if (cause instanceof MismatchedInputException wrongType && !wrongType.getPath().isEmpty()) { return "Field " + path(wrongType) + " has the wrong type."; } if (cause == null) { return "The request body is missing."; } return "The request body is not valid JSON."; }
private static String path(JacksonException ex) { StringBuilder path = new StringBuilder(); for (JacksonException.Reference ref : ex.getPath()) { if (ref.getPropertyName() != null) { path.append(path.isEmpty() ? "" : ".").append(ref.getPropertyName()); } else { path.append('[').append(ref.getIndex()).append(']'); } } return path.toString(); }}$ curl -i -X DELETE http://localhost:8080/api/v1/orders/14/cancel
HTTP/1.1 405
Allow: POST
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:27:51 GMT
{"type":"https://shoplite.example/problems/method-not-allowed","title":"Method not allowed","status":405,"detail":"DELETE is not supported on this URL.","instance":"/api/v1/orders/14/cancel"}
$ curl -X POST http://localhost:8080/api/v1/products -H "Content-Type: text/plain" -d 'hello'
{"type":"https://shoplite.example/problems/unsupported-media-type","title":"Unsupported media type","status":415,"detail":"Content-Type text/plain;charset=UTF-8 is not supported. Send application/json.","instance":"/api/v1/products"}
$ curl http://localhost:8080/api/v1/prodcts
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"There is no endpoint GET /api/v1/prodcts.","instance":"/api/v1/prodcts"}
$ curl http://localhost:8080/api/v1/products/abc
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/products/abc","errors":[{"field":"id","message":"must be a number"}]}
$ curl http://localhost:8080/api/v1/products/average-price
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/products/average-price","errors":[{"field":"categoryId","message":"is required"}]}
$ curl "http://localhost:8080/api/v1/products/average-price?categoryId=7"
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products/average-price"}What this code does
- The class extends
ResponseEntityExceptionHandlerand overrides only the Spring MVC cases ShopLite cares about. Each override receives theheadersSpring prepared, so the 405 keepsAllow: POSTand the 415 keepsAccept. - The
@ExceptionHandler(Exception.class)catch-all no longer needs theinstanceof ErrorResponsecheck: the base class handles Spring's exceptions first because its handler types are closer to them. application.propertiessetsspring.jackson.mapper.sort-properties-alphabetically=falsenext tofail-on-unknown-properties=true, which is why every body starts withtype.
spring.mvc.problemdetails.enabled=true registers that base class for you, so Spring MVC's own errors become problem details. On its own the property is not enough: the bodies have no type, the titles are Spring's ("Not Found"), and your own exceptions are not covered at all.
The better way is to make your advice extend ResponseEntityExceptionHandler and override methods such as handleMethodArgumentNotValid and handleHttpRequestMethodNotSupported. Spring's own errors then keep their status and headers (no more instanceof ErrorResponse trick), and you give each one ShopLite's type and wording. Once you extend it, leave the property off; your advice already does its job.
ErrorResponseException: an exception with its own ProblemDetail
ErrorResponseException is a Spring exception that carries a complete ProblemDetail and a status. Throw a subclass of it, and ResponseEntityExceptionHandler renders its body as it is; no handler method is needed.
A coupon check whose exception builds its own problem details.
Example 6 · CouponExpiredException.java and CouponController.java
Runs in: the errors-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/coupon/CouponExpiredException.javapackage com.shoplite.lab.coupon;
import java.net.URI;
import org.springframework.http.HttpStatus;import org.springframework.http.ProblemDetail;import org.springframework.web.ErrorResponseException;
/** An exception that builds its own ProblemDetail. Spring renders it with no handler method. */public class CouponExpiredException extends ErrorResponseException {
public CouponExpiredException(String code) { super(HttpStatus.GONE, problemFor(code), null); }
private static ProblemDetail problemFor(String code) { ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.GONE, "Coupon " + code + " has expired."); problem.setType(URI.create("https://shoplite.example/problems/coupon-expired")); problem.setTitle("Coupon expired"); problem.setProperty("code", code); return problem; }}
// src/main/java/com/shoplite/lab/coupon/CouponController.javapackage com.shoplite.lab.coupon;
import java.util.Set;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class CouponController {
private static final Set<String> EXPIRED = Set.of("FEST20", "DIWALI10");
@GetMapping("/api/v1/coupons/{code}") public String check(@PathVariable String code) { if (EXPIRED.contains(code)) { throw new CouponExpiredException(code); } return "Coupon " + code + " is valid"; }}$ curl -i http://localhost:8080/api/v1/coupons/FEST20
HTTP/1.1 410
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:27:52 GMT
{"type":"https://shoplite.example/problems/coupon-expired","title":"Coupon expired","status":410,"detail":"Coupon FEST20 has expired.","instance":"/api/v1/coupons/FEST20","code":"FEST20"}What this code does
- The exception builds its whole
ProblemDetailin the constructor, including a customcodeproperty, and passes it tosuper(status, body, cause). - No handler method mentions it:
ResponseEntityExceptionHandler.handleErrorResponseExceptionrenders the body it carries.
ErrorResponseException is handy for a small, web-only feature, such as this coupon check: the exception knows its own status, type, title and extra fields.
ShopLite's services do not use it. A service exception that extends ErrorResponseException depends on HTTP classes, and the status choice spreads over many exception classes. Keeping ShopLiteException free of HTTP and mapping it in GlobalExceptionHandler keeps the whole contract in one class.
Next step
Check your understanding
12 quick questions