|
| 1 | +package com.retailsvc.http; |
| 2 | + |
| 3 | +import java.util.Objects; |
| 4 | +import java.util.Optional; |
| 5 | + |
| 6 | +/** |
| 7 | + * Thrown by user handlers to signal a 4xx client error. The default {@link ExceptionHandler} |
| 8 | + * renders this as an RFC 7807 {@code application/problem+json} response carrying the supplied |
| 9 | + * status, detail, and optional JSON-pointer / validation-keyword fields. |
| 10 | + * |
| 11 | + * <p>Use for cases like {@code 422 Unprocessable Content} (payload is syntactically valid but |
| 12 | + * violates a business rule), {@code 409 Conflict}, {@code 412 Precondition Failed}, etc. For 5xx |
| 13 | + * errors, throw an ordinary {@link RuntimeException} and let the default handler render 500. |
| 14 | + */ |
| 15 | +public final class BadRequestException extends RuntimeException { |
| 16 | + |
| 17 | + private static final int DEFAULT_STATUS = 400; |
| 18 | + |
| 19 | + private final int status; |
| 20 | + private final String pointer; |
| 21 | + private final String keyword; |
| 22 | + |
| 23 | + public BadRequestException(String detail) { |
| 24 | + this(DEFAULT_STATUS, detail, null, null); |
| 25 | + } |
| 26 | + |
| 27 | + public BadRequestException(int status, String detail) { |
| 28 | + this(status, detail, null, null); |
| 29 | + } |
| 30 | + |
| 31 | + public BadRequestException(int status, String detail, String pointer, String keyword) { |
| 32 | + super(Objects.requireNonNull(detail, "detail must not be null")); |
| 33 | + if (status < 400 || status > 499) { |
| 34 | + throw new IllegalArgumentException("status must be 4xx, got " + status); |
| 35 | + } |
| 36 | + this.status = status; |
| 37 | + this.pointer = pointer; |
| 38 | + this.keyword = keyword; |
| 39 | + } |
| 40 | + |
| 41 | + public int status() { |
| 42 | + return status; |
| 43 | + } |
| 44 | + |
| 45 | + public Optional<String> pointer() { |
| 46 | + return Optional.ofNullable(pointer); |
| 47 | + } |
| 48 | + |
| 49 | + public Optional<String> keyword() { |
| 50 | + return Optional.ofNullable(keyword); |
| 51 | + } |
| 52 | +} |
0 commit comments