Sub topic 4
Modeling failures as custom exceptions
This chapter assumes you can build a basic Spring Boot REST controller, know the difference between checked and unchecked exceptions, and know common HTTP status codes. Here you design the exceptions your application throws. Later chapters map them to HTTP responses.
Why not throw generic exceptions?
If a controller throws RuntimeException("not found"), Spring Boot returns a 500 response. Nothing in the type tells a handler that the client asked for something that does not exist. A handler would have to parse the message, which breaks as soon as someone rewords it.
A custom exception gives the failure a name and a type. A handler can catch that type and pick the right status code. The exception can also carry data, such as the id that was not found, so the handler does not need to parse text.
A domain exception
The exception below describes a business failure, not an HTTP one. It carries the identifier of the missing order.
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;
}
}Three design choices are worth noting:
- It extends
RuntimeException, so it is unchecked. Controllers and services do not needthrowsclauses, and Spring's transaction handling rolls back on unchecked exceptions by default. - The id is stored in a
finalfield with a getter. A handler can readgetOrderId()and add it to the response. - The message is built in the constructor. Every caller gets the same wording.
Throwing it from a controller
The controller below looks up an order and throws the exception when the id is unknown. It also validates the request body with @Valid, which needs spring-boot-starter-validation on the classpath. Validation errors are covered in a later chapter.
package com.example.orders;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.util.Map;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
record Order(long id, String item) {}
record CreateOrderRequest(@NotBlank String item, @Positive int quantity) {}
@RestController
@RequestMapping("/orders")
class OrderController {
private final Map<Long, Order> orders = Map.of(1L, new Order(1L, "Book"));
@GetMapping("/{id}")
Order get(@PathVariable long id) {
return Optional.ofNullable(orders.get(id))
.orElseThrow(() -> new OrderNotFoundException(id));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Order create(@Valid @RequestBody CreateOrderRequest request) {
return new Order(2L, request.item());
}
}In a real application the lookup would live in a service class. The throw would happen there, and the controller would stay thin. The exception works the same way wherever it is thrown.
Without a handler, a request for /orders/99 still returns a 500, because Spring does not yet know what OrderNotFoundException means. The next chapters fix that.
Naming and organizing exceptions
These habits keep a set of exceptions manageable:
- Name the exception after the failure, such as
OrderNotFoundExceptionorInsufficientStockException, not after the HTTP status. - Keep exceptions in the package of the feature that throws them.
- Add fields only for data a handler will use. Avoid storing entities or other large objects.
- Create a shared base class, such as
DomainException, only when several handlers would otherwise repeat the same logic.
Keeping HTTP out of the domain
Putting @ResponseStatus(NOT_FOUND) on the exception class is a quick option, and the next chapter shows it. The cost is that a domain class now depends on web concepts. The class above stays free of web annotations, and a separate handler decides the status code. This also lets different entry points, such as a REST controller and a message listener, treat the same exception differently.
Mapping overview
The diagram shows where the custom exception fits in the request path.
Exercise
Why does OrderNotFoundException store the order id in a field instead of only putting it in the message?
Show answer
A handler can read the id with getOrderId() and add it to the response body as a separate property. If the id were only in the message text, the handler would have to parse the string, which breaks when the wording changes.
Exercise
What status code does a client receive for GET /orders/99 if no handler exists for OrderNotFoundException, and why?
Show answer
A 500 Internal Server Error. The exception is unchecked and unhandled, so Spring Boot falls back to its default error handling, which treats it as a server failure.