Exception design for services

A hierarchy with a business base, a technical base, and a translation layer at the edge — so a stack trace never reaches a client.

7 min read🧰 Exceptions, I/O and Reflection

A service has three audiences for a failure: the code that called the method, the client on the other end of the HTTP connection, and the engineer reading the log at 2am. Each needs something different, and an exception design is the plan for giving each of them exactly that — without a stack trace ever reaching a client or a 500 ever hiding a validation error.

Two families

Every exception a service throws is one of two kinds:

  • Business — the request was understood and refused: not found, already exists, insufficient funds, not allowed in this state. The caller did something the domain does not permit. These map to 4xx.
  • Technical — the system failed: the database is down, a downstream timed out, a file is corrupt. The caller did nothing wrong. These map to 5xx, and the details are for the log, not the client.

Model that distinction in the type hierarchy:

java
public abstract class ServiceException extends RuntimeException {
    protected ServiceException(String message, Throwable cause) { super(message, cause); }
}
 
public abstract class BusinessException extends ServiceException {
    private final String code;                       // stable, machine-readable
    protected BusinessException(String code, String message) { super(message, null); this.code = code; }
    public String code() { return code; }
}
 
public final class NotFoundException extends BusinessException {
    public NotFoundException(String entity, Object id) {
        super("not_found", entity + " " + id + " was not found");
    }
}
public final class ConflictException extends BusinessException { ... }     // "already_exists", "version_conflict"
public final class InvalidStateException extends BusinessException { ... } // "order_already_shipped"
 
public final class InfrastructureException extends ServiceException {
    public InfrastructureException(String message, Throwable cause) { super(message, cause); }
}

Unchecked throughout — the previous lesson's rule — and a small number of types. Resist one class per error; the code field carries the specific case, and codes are what clients switch on.

Messages

An exception message should let the log reader reconstruct what happened without a debugger: the operation, the identifiers, the state. "Order 4231 cannot be cancelled: status is SHIPPED" — not "Invalid state". Include values, never secrets: no passwords, tokens, card numbers, personal data. The message will be logged, and logs are read by more people than the code.

Translation at the edge

Business logic throws domain exceptions and knows nothing about HTTP. One handler at the boundary maps them:

java
@RestControllerAdvice
class ApiExceptionHandler {
 
    @ExceptionHandler(NotFoundException.class)
    ProblemDetail notFound(NotFoundException e) {
        return problem(HttpStatus.NOT_FOUND, e);
    }
 
    @ExceptionHandler(ConflictException.class)
    ProblemDetail conflict(ConflictException e) {
        return problem(HttpStatus.CONFLICT, e);
    }
 
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail validation(MethodArgumentNotValidException e) { ... }   // 400 with field errors
 
    @ExceptionHandler(Exception.class)
    ProblemDetail unexpected(Exception e, HttpServletRequest req) {
        String id = UUID.randomUUID().toString();
        log.error("unhandled [{}] {} {}", id, req.getMethod(), req.getRequestURI(), e);
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        p.setDetail("Something went wrong. Reference: " + id);
        return p;                                                        // no message, no trace
    }
 
    private ProblemDetail problem(HttpStatus status, BusinessException e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(status, e.getMessage());
        p.setProperty("code", e.code());
        return p;
    }
}

ProblemDetail is Spring's implementation of RFC 9457 — a standard JSON shape (type, title, status, detail, instance) that clients can rely on. The unexpected-exception handler is the important one: it logs everything with a correlation id, and returns only that id. A client sees "Reference: 3f1c..."; support searches the log for it.

What never leaves the server

  • Stack traces. server.error.include-stacktrace=never in Boot, and the handler above.
  • Exception class names. com.shop.billing.LedgerRepository in a response is free reconnaissance.
  • SQL, table names, constraint names. duplicate key value violates unique constraint "users_email_key" tells an attacker your schema. Translate DataIntegrityViolationException into a business conflict with your own message.
  • Internal hostnames and downstream error bodies.

Logging

Log an exception once, at the boundary that handles it. The anti-pattern is log-and-rethrow at every layer, which produces four stack traces for one failure and buries the useful line. Pass the exception object as the last logger argument so the trace is included; log.error("failed: " + e.getMessage()) drops it.

Business exceptions are usually not errors from the service's point of view — a 404 is a normal outcome — log them at INFO or DEBUG, or not at all, and count them as metrics instead. Technical exceptions are ERROR with the trace.

Wrapping infrastructure failures

java
try {
    return paymentClient.charge(amount, token);
} catch (HttpTimeoutException | ConnectException e) {
    throw new InfrastructureException("payment gateway unreachable for order " + orderId, e);
}

Keep the cause. Add the context the low-level exception lacks (which order, which operation). Do not catch broadly here — a NullPointerException in your own code is a bug, not an infrastructure failure, and wrapping it mislabels it.

Under the hood: what throwing actually costs — and how to skip it

"Exceptions are expensive" is a half-truth that leads to the wrong optimisation. The athrow instruction and stack unwinding are cheap — a control-flow jump to the nearest matching handler, the same mechanism a return from deep in a call chain would need anyway. What is expensive is something that happens once, in every Throwable's constructor, before the throw even executes: fillInStackTrace().

fillInStackTrace() is a native method that walks the entire current call stack — every frame, from where the exception is constructed back to the thread's entry point — and records each one's class, method, file and line into the exception object. For a deep call chain (a service calling a repository calling a driver calling a socket), that walk touches a lot of frames, and it happens on every single new SomeException(...), whether or not anyone ever reads getStackTrace() afterward. A BusinessException like NotFoundException thrown thousands of times a second for an entirely ordinary "no such order" outcome pays this cost every time, for a trace that — because the throw site is the same few lines of validation code — tells the log reader nothing they did not already know from the exception's type and message.

The JDK gives you a way out, deliberately: Throwable has a protected four-argument constructor, Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace), added in Java 7. Passing writableStackTrace = false skips fillInStackTrace() at construction entirely — not "captures it but doesn't print it": getStackTrace() returns an empty array, because there was never anything to fill in. It is protected, so only your own subclass can use it — you cannot flip it for a plain new IllegalArgumentException(...), which is exactly right: this is a decision an exception's author makes about a specific, known-hot, low-diagnostic-value exception type, not a knob for every throw site to reach for individually.

java
public final class NotFoundException extends BusinessException {
    public NotFoundException(String entity, Object id) {
        super("not_found", entity + " " + id + " was not found");
        // BusinessException's constructor can pass writableStackTrace=false to
        // Throwable's 4-arg constructor for exactly this family of exception.
    }
}

Try it yourself

java
class NoTrace extends RuntimeException {
    NoTrace(String m) { super(m, null, false, false); }
}
RuntimeException withTrace = new RuntimeException("normal");
RuntimeException noTrace = new NoTrace("fast");
System.out.println("normal frames: " + (withTrace.getStackTrace().length > 0));
System.out.println("no-trace frames: " + noTrace.getStackTrace().length);

Predict before running: is the no-trace exception's stack "truncated"?

NoTrace's constructor calls the four-argument super(m, null, false, false). Before running the snippet: does noTrace.getStackTrace() return a short array (a few frames instead of many), or something more absolute than that?

Empty, not short — writableStackTrace=false prevents capture, not printing

noTrace.getStackTrace().length is 0, not "fewer frames than withTrace". Passing writableStackTrace = false to the four-argument constructor stops fillInStackTrace() from ever running at construction time — there is no partial walk, no depth limit, nothing recorded at all. This matters operationally: code that defensively checks if (e.getStackTrace().length > 0) before logging a trace will correctly skip logging anything for a NoTrace-style exception, but code that assumes "an exception always has some trace, even a short one" and indexes into getStackTrace()[0] unconditionally will throw ArrayIndexOutOfBoundsException on exactly this family of exception — a second, easy-to-miss cost of choosing this design that the exception's own throw site never sees.

Misconceptions

  • "Throwing an exception is what makes exceptions slow." No — athrow and stack unwinding are ordinary control flow. The expensive step is fillInStackTrace(), which runs once in the constructor, before the throw statement executes at all; a new SomeException(...) sitting in a local variable, never thrown, has already paid the cost.
  • "A stackless exception's trace is just truncated, so printStackTrace() still shows a line or two." It shows none — the exercise above confirms getStackTrace().length is exactly 0, not a partial capture. Code that assumes every exception has at least a frame or two can break on one built this way.

Sources

  • Oracle Java SE Platform documentation — java.lang.Throwable, the protected four-argument constructor (Throwable(String, Throwable, boolean, boolean)), added in Java 7.
  • Joshua Bloch, Effective Java, 3rd ed. — Item 77, "Don't ignore exceptions", and the chapter on exception design generally.
  • Spring Framework reference documentation — ProblemDetail and RFC 9457.
Progress is saved on this device and to your account when signed in.