Sub topic 1
Why error handling deserves a design
Prerequisites
This chapter assumes basic Java exceptions, Spring Boot REST controllers, HTTP status codes, JSON, and Maven or Gradle.
A REST API communicates failures through HTTP. A missing order should produce 404 Not Found, while invalid input should produce 400 Bad Request. If each controller reports errors differently, clients must learn many response formats. A designed error contract gives clients predictable status codes and fields while keeping internal details private.
| Failure | Status | Client-facing meaning |
|---|---|---|
| Missing order | 404 | The requested resource does not exist |
| Invalid request body | 400 | The client must correct its input |
| Unexpected failure | 500 | The server failed; retry or report the issue |
What Spring Boot does by default
When a controller throws an exception and no application handler resolves it, Spring MVC passes the failure through its exception resolver chain. Spring Boot commonly exposes the result through its /error endpoint and BasicErrorController.
The default JSON often contains fields such as timestamp, status, error, path, and sometimes message or trace. Exact fields depend on the Spring Boot version and configuration. This default is useful during development, but it is usually too inconsistent or revealing for a production API.
Tuning the default error response with `server.error.*` properties
Use configuration to reduce accidental information leakage:
server.error.include-message=never
server.error.include-binding-errors=never
server.error.include-stacktrace=never
server.error.include-exception=falseThese settings affect Boot's default error response. They do not replace a deliberate error contract. For consistent APIs, add application-level handlers and return a standard body such as ProblemDetail.
Modeling failures as custom exceptions
A domain exception names a meaningful failure and carries structured data. The handler can then map it to HTTP without parsing text.
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;
}
}Throw this exception when an order lookup fails. A later @RestControllerAdvice can map it to 404 and include orderId. Keep the exception message useful for logs, but expose only fields that clients need.
Exercise
Which status should an unknown order use, and why should its identifier be stored separately from the message?
Show answer
Use 404 Not Found. A separate identifier lets a handler create stable response data without parsing human-readable text.