APIs · Lesson 6
Exception Handling in APIs
Turning Failures into API Responses
API clients need stable error responses even when internal failures vary. Exception handling maps known domain failures to useful status codes and maps unexpected failures to a safe generic error. Central handling keeps controllers concise and consistent.
A Stable Error Shape
A problem response should include a code, a human-readable message, and a correlation identifier. The identifier lets operators find the protected server-side details.
public record ApiError(String code, String message, String traceId) {
public static ApiError notFound(String traceId, String resourceName) {
return new ApiError("resource_not_found", resourceName + " was not found", traceId);
}
public static void main(String[] arguments) {
System.out.println(ApiError.notFound("trace-184", "Course"));
}
}
Error Mapping
| Failure | Status | Client action |
|---|---|---|
| Invalid request | 400 | Correct input |
| Missing authentication | 401 | Sign in |
| Not permitted | 403 | Request access |
| Missing resource | 404 | Refresh or change identifier |
| Conflict | 409 | Resolve current state |
| Unexpected failure | 500 | Retry later or contact support |
Common Mistake and Practices
Common Mistake: Returning raw exception messages and stack traces in JSON. These details can expose SQL, file paths, and security-sensitive internals.
- Use one documented error schema.
- Assign a trace ID to each request.
- Log unexpected causes on the server.
- Distinguish retryable from permanent failures.
- Test error responses as carefully as success responses.
Real-World Use Case
When a learner requests a missing lesson, the API returns a predictable resource_not_found error. When the database is unavailable, it returns a generic 503 response while operators use the trace ID to inspect logs.
Quiz Check