Skip to lesson

Practice: exception handling

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

An optional checkpoint: three habits make error handling reliable. Pick the right kind for each failure, decide it in one place, and never let a reply leak or hide a bug.

Mapping error cases to status codes and exceptions

Five ShopLite requests, each broken in a different way. The program applies the contract's order of checks to each one.

Example 1 · The order of checks decides which error the client sees

CheckOrderDemo.javaJava
import java.math.BigDecimal;import java.util.List;import java.util.Map;import java.util.Set;
record NewProduct(String sku, String name, long categoryId, BigDecimal price) {}
public class CheckOrderDemo {    static final Set<Long> CATEGORIES = Set.of(2L, 4L, 5L);    static final Set<String> SKUS = Set.of("MOB-RN13", "ACC-AD141");    static final Map<Long, String> PRODUCTS = Map.of(1L, "MOB-RN13", 6L, "ACC-AD141");
    // The contract's order: validate fields (400) -> URL resource (404) -> other data (422) -> state (409)    static String replace(long id, NewProduct p) {        if (!p.sku().matches("^[A-Z0-9-]{3,20}$") || p.price().signum() <= 0) {            return "400 validation-failed";        }        if (!PRODUCTS.containsKey(id)) {            return "404 not-found: Product " + id + " was not found.";        }        if (!CATEGORIES.contains(p.categoryId())) {            return "422 rule-broken: Category " + p.categoryId() + " does not exist.";        }        if (SKUS.contains(p.sku()) && !p.sku().equals(PRODUCTS.get(id))) {            return "409 already-exists: A product with SKU " + p.sku() + " already exists.";        }        return "200 OK";    }
    public static void main(String[] args) {        List<Object[]> cases = List.of(                new Object[] {6L, new NewProduct("ACC-AD141", "boAt Airdopes 141", 4, new BigDecimal("1199.00"))},                new Object[] {6L, new NewProduct("MOB-RN13", "Earbuds", 42, new BigDecimal("1199.00"))},                new Object[] {99L, new NewProduct("MOB-RN13", "Earbuds", 42, new BigDecimal("1199.00"))},                new Object[] {99L, new NewProduct("kb 1", "Earbuds", 42, new BigDecimal("-5"))},                new Object[] {6L, new NewProduct("MOB-RN13", "Earbuds", 4, new BigDecimal("1199.00"))});        for (Object[] c : cases) {            NewProduct p = (NewProduct) c[1];            System.out.println("PUT /products/" + c[0] + " sku=" + p.sku() + " category=" + p.categoryId()                    + " -> " + replace((Long) c[0], p));        }    }}
Output
PUT /products/6 sku=ACC-AD141 category=4 -> 200 OK
PUT /products/6 sku=MOB-RN13 category=42 -> 422 rule-broken: Category 42 does not exist.
PUT /products/99 sku=MOB-RN13 category=42 -> 404 not-found: Product 99 was not found.
PUT /products/99 sku=kb 1 category=42 -> 400 validation-failed
PUT /products/6 sku=MOB-RN13 category=4 -> 409 already-exists: A product with SKU MOB-RN13 already exists.

What this code does

  • replace checks in the contract's order: fields (400), the URL's product (404), the category (422), then the SKU (409).
  • Cases 2, 3 and 4 break several rules at once; each reports only the first failing check. Product 99 with category 42 is a 404, because a missing URL resource is checked before data in the body.

Every ShopLite failure maps to one kind: a status, a problem type and the exception that produces it. The status follows one line of logic each: 400 the request itself is wrong, 404 the URL's resource does not exist, 409 it clashes with the current state, 422 it is valid but refers to data that breaks a rule, 500 our bug:

  • Bad field, bad parameter, wrong type in a parameter → 400 validation-failed (MethodArgumentNotValidException, HandlerMethodValidationException, type mismatch).
  • Body that cannot be read → 400 malformed-request (HttpMessageNotReadableException).
  • Missing product, category, order in the URL → 404 not-found (ResourceNotFoundException).
  • Duplicate, in use, out of stock, wrong status → 409 (AlreadyExists, ResourceInUse, OutOfStock, InvalidState); unknown category or inactive product in the body → 422 (BusinessRuleException).

When several things are wrong at once, the order of checks decides which one the client hears about: parse the body, validate the fields, load the resource in the URL, check rules on other data, then check state and uniqueness. A PUT to a missing product with an unknown category is a 404, not a 422.

Fixing handlers that leak or swallow

A handler that leaks internal details in its reply, and the real response it produces.

Example 2 · A leaking catch-all and its real reply

Runs in: the errors-lab practice project (Spring Boot 4.1)

Java
// in GlobalExceptionHandler (bad version)@ExceptionHandler(Exception.class)public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) {    ProblemDetail problem = ProblemKind.INTERNAL_ERROR.problem(ex.toString());    problem.setProperty("exception", ex.getClass().getName());    problem.setProperty("at", String.valueOf(ex.getStackTrace()[0]));    return problem;                                                                    // and logs nothing}
Sample output
$ 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":"java.lang.ArithmeticException: / by zero","instance":"/api/v1/products/average-price","exception":"java.lang.ArithmeticException","at":"java.base/java.math.BigDecimal.divideAndRound(BigDecimal.java:4955)"}

Server console: (nothing)

What this code does

  • The client learns the exception class, its message and the exact JDK frame; the log learns nothing, because the handler never logs.
  • The safe version (Example 5 of the ProblemDetail lesson) returns a fixed sentence and logs the request with the stack trace.

A leaking handler sends internal details to the client: the exception message, the exception class, a stack frame. A swallowing one catches, logs nothing and returns a normal-looking answer. Both are easy to write by accident, and both are easy to spot in review.

The fix is always the same shape: expected errors are ShopLite exceptions with safe messages; everything else reaches the catch-all, which logs the full stack trace once and returns a fixed sentence. Add no try/catch in a service unless it adds meaning, such as wrapping a checked SQLException with its cause.

Predicting the response for a failing request

Five failing requests: predict the status and the problem type first, then compare with the real replies.

Example 3 · Predict, then check: five failing requests

Runs in: the errors-lab practice project (Spring Boot 4.1)

Terminal
curl http://localhost:8080/api/v1/categories/99curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":9,"quantity":0}]}'curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":77,"quantity":1}]}'curl -X POST http://localhost:8080/api/v1/orders/16/cancelcurl -X POST http://localhost:8080/api/v1/orders/16/cancel
Output
$ curl http://localhost:8080/api/v1/categories/99
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Category 99 was not found.","instance":"/api/v1/categories/99"}
$ curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":9,"quantity":0}]}'
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/orders","errors":[{"field":"items[0].quantity","message":"must be between 1 and 10"}]}
$ curl -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":77,"quantity":1}]}'
{"type":"https://shoplite.example/problems/rule-broken","title":"Business rule broken","status":422,"detail":"Product 77 does not exist.","instance":"/api/v1/orders"}
$ curl -X POST http://localhost:8080/api/v1/orders/16/cancel
{"id":16,"status":"CANCELLED"}
$ curl -X POST http://localhost:8080/api/v1/orders/16/cancel
{"type":"https://shoplite.example/problems/invalid-state","title":"Invalid state change","status":409,"detail":"Order 16 is CANCELLED and can no longer be cancelled.","instance":"/api/v1/orders/16/cancel"}

What this code does

  • Quantity 0 never reaches the service: Bean Validation stops it (400, field items[0].quantity). Product 77 passes validation, so the service finds it missing and throws a 422, not a 404, because it is in the body, not the URL.
  • The same cancel twice: the first works, the second hits the order's new status and gets 409 invalid-state. Repeating a request can change its answer when state changes.

To predict a response, walk the request through the layers. Does Jackson read the body? Do the constraints pass? Does the URL's resource exist? Which exception does the service throw, and which handler is closest to it? The answer gives the status, the type, the title and the detail.

The same walk debugs a wrong reply: a 500 where you expected 404 means an exception reached the catch-all, so either the service threw the wrong type or a handler is missing.

Checked versus unchecked exceptions in Spring

A service wraps the checked IOException of a price-list file into an unchecked ShopLite exception.

Example 4 · Wrapping a checked exception at the boundary

WrapCheckedDemo.javaJava
import java.io.IOException;import java.io.UncheckedIOException;import java.nio.file.Files;import java.nio.file.Path;
abstract class ShopLiteException extends RuntimeException {    protected ShopLiteException(String message, Throwable cause) {        super(message, cause);    }}
class PriceListUnavailableException extends ShopLiteException {    PriceListUnavailableException(String file, Throwable cause) {        super("The price list " + file + " could not be read.", cause);    }}
class PriceListService {    // Files.readString throws the checked IOException; the service turns it into an unchecked one    String load(Path file) {        try {            return Files.readString(file);        } catch (IOException e) {            throw new PriceListUnavailableException(file.getFileName().toString(), e);        }    }}
public class WrapCheckedDemo {    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("prices");        Path good = Files.writeString(dir.resolve("diwali.csv"), "MOB-RN13,16999.00");        PriceListService service = new PriceListService();
        System.out.println("Loaded: " + service.load(good));        try {            service.load(dir.resolve("holi.csv"));        } catch (ShopLiteException e) {            System.out.println("Message: " + e.getMessage());            System.out.println("Cause:   " + e.getCause().getClass().getSimpleName());            System.out.println("Checked? " + !(e.getCause() instanceof RuntimeException));            System.out.println("Unchecked wrapper? " + (e instanceof RuntimeException));        }        Files.delete(good);        Files.delete(dir);        System.out.println("UncheckedIOException is the JDK's own wrapper: "                + RuntimeException.class.isAssignableFrom(UncheckedIOException.class));    }}
Output
Loaded: MOB-RN13,16999.00
Message: The price list holi.csv could not be read.
Cause:   NoSuchFileException
Checked? true
Unchecked wrapper? true
UncheckedIOException is the JDK's own wrapper: true

What this code does

  • Files.readString declares the checked IOException. The service catches it once and throws an unchecked ShopLite exception with a safe message and the original as the cause.
  • Callers, controllers and the advice need no throws clause, and the log still shows NoSuchFileException through getCause().
  • The program creates its file in a temporary folder and deletes it at the end, and prints only file names.

A checked exception (a subclass of Exception but not RuntimeException) must be caught or declared with throws; an unchecked one need not. Spring code prefers unchecked exceptions: they pass through controllers to the advice without throws on every method, and @Transactional rolls back by default only for unchecked exceptions (and errors).

Libraries still throw checked ones, such as IOException and SQLException. Catch them at the boundary where they happen and rethrow a meaningful unchecked exception with the original as the cause. Spring itself does this: JdbcTemplate turns SQLException into its unchecked DataAccessException family.

Finish up

Mark complete & continue

Next: Mini project: ShopLite global error handling