Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

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

FailureStatusClient action
Invalid request400Correct input
Missing authentication401Sign in
Not permitted403Request access
Missing resource404Refresh or change identifier
Conflict409Resolve current state
Unexpected failure500Retry 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

Quick Knowledge Test

Loading quiz questions...