Sub topic 4
Modeling failures as custom exceptions
This chapter shows how to turn "something went wrong" into named, typed exceptions that your service code can throw and your error handling can map to HTTP responses later. It assumes you can write a Spring Boot REST controller, you know the difference between checked and unchecked exceptions in Java, and you know the common HTTP status codes (400, 404, 409, 500).
Mapping exceptions to HTTP responses comes in later chapters (@ResponseStatus, @ExceptionHandler, @RestControllerAdvice). Here the goal is to design the exceptions themselves.
Why model failures explicitly
A service method can fail in different ways, and each way means something different to the caller:
- The requested order does not exist (the client asked for the wrong thing).
- The order exists but is in a state that forbids the action (the request conflicts with current data).
- A downstream system is unavailable (the server or its dependencies failed).
If all three throw IllegalStateException or RuntimeException("something broke"), the error layer has to inspect message strings to tell them apart. That is fragile, because rewording a message changes behavior.
A custom exception class gives each failure a type. The type is the contract between the code that detects the problem and the code that decides how to report it. The service says what happened ("order 42 was not found"). The error handling layer decides how to say it over HTTP (a 404 with a JSON body).
Correction of format: the diagram below uses the required fence.
Use unchecked exceptions
Make your custom exceptions extend RuntimeException, not Exception. There are three reasons:
- Controllers and services would otherwise need
throwsclauses on every method between the failure and the handler. - Spring's
@Transactionalrolls back on unchecked exceptions by default but commits on checked ones. A checked business exception thrown inside a transaction silently commits partial work unless you addrollbackFor. - Lambdas and streams (for example
Optional.orElseThrow) work cleanly with unchecked exceptions only.
Checked exceptions still appear at boundaries you do not control, such as IOException. Catch them near the boundary and translate them into your own unchecked type, as shown later in this chapter.
A first exception: carry data, not just text
The simplest useful custom exception names the failure and keeps the identifier that caused it:
package com.example.orders;
public class OrderNotFoundException extends RuntimeException {
private final long orderId;
public OrderNotFoundException(long orderId) {
super("Order " + orderId + " was not found");
this.orderId = orderId;
}
public long getOrderId() {
return orderId;
}
}The message is built in one place, so every throw site produces the same wording. The orderId field means a handler can put the id in a response property without parsing the message. Prefer structured fields over message parsing whenever a handler needs the data.
A controller or service throws it where the lookup fails:
return Optional.ofNullable(orders.get(id))
.orElseThrow(() -> new OrderNotFoundException(id));Exceptions that describe a conflict
Not every failure is "not found". This exception represents a request that is valid in shape but not allowed in the order's current state:
package com.example.orders;
public class OrderStateException extends RuntimeException {
private final long orderId;
private final String currentStatus;
public OrderStateException(long orderId, String currentStatus) {
super("Order " + orderId + " cannot be changed while it is " + currentStatus);
this.orderId = orderId;
this.currentStatus = currentStatus;
}
public long getOrderId() {
return orderId;
}
public String getCurrentStatus() {
return currentStatus;
}
}Later you can map this to 409 Conflict. The class name describes the business problem, not the HTTP status. That is deliberate: the same exception could be reported as a different status by a different client-facing layer, such as a message consumer.
Wrapping a lower-level cause
When you translate a technical exception into a domain exception, always pass the original as the cause. Otherwise the stack trace of the real problem is lost.
package com.example.orders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class ReceiptUnavailableException extends RuntimeException {
private final long orderId;
ReceiptUnavailableException(long orderId, Throwable cause) {
super("Receipt for order " + orderId + " is unavailable", cause);
this.orderId = orderId;
}
long getOrderId() {
return orderId;
}
}
class ReceiptService {
String load(long orderId) {
try {
return Files.readString(Path.of("receipts", orderId + ".txt"));
} catch (IOException e) {
throw new ReceiptUnavailableException(orderId, e);
}
}
}The client later sees only the domain message. The log shows the full chain, including the IOException and the file path inside it. The message you pass to super is what a handler would typically send to the client, so it should not contain the cause's message.
Build a small hierarchy only when it pays off
Once you have several exceptions, you may be tempted to add a base class. A base class helps when one handler should treat a whole family the same way. It does not help when it only adds a layer of naming.
package com.example.orders;
public abstract class DomainException extends RuntimeException {
protected DomainException(String message) {
super(message);
}
protected DomainException(String message, Throwable cause) {
super(message, cause);
}
}With this base, OrderNotFoundException and OrderStateException can extend DomainException. A single handler for DomainException then catches every business failure, for example to log them at a lower level than unexpected errors (see the logging chapter).
Use this table to decide how much structure you need:
| Situation | Suggested design |
|---|---|
| One or two failure kinds, each mapped differently | Separate classes extending `RuntimeException` |
| Many failures that share handling (logging, response shape) | A shared abstract base class |
| A one-off failure at a single throw site | `ResponseStatusException` instead of a new class (covered in a later chapter) |
| Same status, different details (several kinds of "not found") | One class per resource, so `OrderNotFoundException` and `CustomerNotFoundException` stay distinct |
| Many near-identical classes | Consider one generic exception with a `resourceType` field, if handlers do not need to tell them apart |
Avoid deep hierarchies. Two levels (base plus concrete classes) is usually enough, and every extra level makes handler selection harder to predict.
Keep HTTP out of the domain, with a trade-off
A purist design keeps HttpStatus out of exception classes, so the service layer does not depend on web types. The exception only says what happened, and one place maps types to statuses. This keeps services reusable from non-HTTP code such as scheduled jobs.
The pragmatic alternative is to annotate the exception with @ResponseStatus(HttpStatus.NOT_FOUND). It is less code and fine for small applications, but it ties the class to HTTP. A later chapter compares both approaches. For now, choose names that describe the problem and leave the status out of the class body.
Performance: stack traces for expected failures
Constructing an exception fills in its stack trace, which is the expensive part. For failures that clients trigger routinely, such as "not found", this cost is usually negligible. If profiling shows a hot path, you can suppress the trace through the four-argument RuntimeException constructor:
package com.example.orders;
public class QuotaExceededException extends RuntimeException {
public QuotaExceededException(String message) {
super(message, null, false, false);
}
}The last two arguments disable suppression and stack-trace writing. Do this only for expected, high-volume failures. An exception without a stack trace is much harder to debug, so never apply it to unexpected errors.
Common mistakes
- Exceptions as control flow. Throwing to signal a normal outcome, such as "no results", makes code hard to follow. Return an empty collection or
Optionalinstead, and throw when the caller asked for something specific that cannot exist. - Sensitive data in messages. Messages often end up in client responses. Do not include SQL, file paths, internal hostnames, or another user's data. Put those in logs or in the cause.
- Dropping the cause.
throw new MyException("failed")inside acatchblock discards the original stack trace. Always pass the caught exception as the cause. - Catch and swallow.
catch (Exception e) { }hides failures. If you catch, either handle the problem or translate and rethrow. - One giant exception. A single
ApiExceptionwith an error-code string field forces handlers to branch on strings, which is the problem custom types were meant to remove. - Mutable or non-serializable fields. Exceptions are
Serializable. Keep fields to simple values such as ids and strings, not entities or open resources. - Throwing in the wrong layer. Detect business failures in services, where the rules live. Controllers should translate requests and let exceptions pass through.
Checklist for a new exception
- Does an existing exception already describe this failure? Reuse it if so.
- Does it extend
RuntimeException(or your base class)? - Does it carry the fields a handler will need, as simple values?
- Is the message safe to show to a client?
- If it wraps another exception, is the cause passed through?
- Is the name about the business problem, not the technology or the HTTP status?
Exercise
A service method calls a payment gateway client that throws the checked exception GatewayTimeoutException. You want callers to see a domain exception named PaymentUnavailableException that carries the order id. Describe how you would define the class and where and how you would throw it, and name two things that must be true of the design.
Show answer
Define PaymentUnavailableException extends RuntimeException with a long orderId field, a constructor (long orderId, Throwable cause) that calls super("Payment for order " + orderId + " is unavailable", cause), and a getter. In the service method, wrap the gateway call in a try block, catch GatewayTimeoutException, and throw new PaymentUnavailableException(orderId, e). Two requirements: the exception must be unchecked so it does not force throws clauses and does not bypass transaction rollback, and the original exception must be passed as the cause so the stack trace is preserved in the logs. The message should also avoid exposing gateway internals such as hostnames.
Exercise
Why is it better for a handler to read getOrderId() from OrderNotFoundException than to parse the id out of the message?
Show answer
The message is human-readable text that can be reworded at any time, and parsing it breaks silently when that happens. A typed field is part of the class's API, is checked by the compiler, and needs no string handling.