JsonApi4j automatically converts exceptions into JSON:API error responses. Every exception thrown during request processing is caught, mapped to an ErrorsDoc, and returned with the appropriate HTTP status code. No manual error formatting is needed.

How It Works

When an exception is thrown during request processing:

  1. The dispatcher servlet catches the exception
  2. The ErrorHandlerFactoriesRegistry finds a matching ErrorsDocSupplier for the exception class
  3. The supplier converts the exception into an ErrorsDoc (containing one or more ErrorObjects) and an HTTP status code
  4. The servlet writes the JSON:API error response

If no handler matches the exact exception class, the registry searches all registered exception classes and selects the most specific ancestor (closest parent in the class hierarchy). If nothing matches, a generic 500 Internal Server Error is returned.

Exception thrown
    │
    ▼
ErrorHandlerFactoriesRegistry.getErrorResponseMapper(exception)
    │
    ├── Exact class match found? → Use that handler
    │
    ├── Ancestor match found? → Use the most specific ancestor handler
    │
    └── No match → 500 Internal Server Error
    │
    ▼
ErrorsDocSupplier.getErrorResponse(exception) → ErrorsDoc
ErrorsDocSupplier.getHttpStatus(exception) → HTTP status code
    │
    ▼
JSON:API error response written to client

4xx errors are logged at WARN level (client errors). 5xx errors are logged at ERROR level with full stack trace.

Each log line carries the id of every error object in the response, and the same ids are put in the logs under jsonapi4j.errorId while the line is logged. When a client reports an error by its id, search the logs for it:

WARN  ErrorsDocResponseWriter - 404 code. Error id(s): a1b2c3d4-e5f6-7890-abcd-ef1234567890. Error message: ...

To get from that line to every other log line of the same request, include your tracing ids (e.g. Micrometer or OpenTelemetry traceId) in the log pattern. The error line then carries both ids.

Error Response Structure

Every error response follows the JSON:API error format. The response body is an ErrorsDoc containing a list of ErrorObjects:

{
  "errors": [
    {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "status": "400",
      "code": "VALUE_IS_ABSENT",
      "detail": "Field 'name' must not be null",
      "source": {
        "parameter": "name"
      }
    }
  ]
}

Each ErrorObject has the following fields:

Field Type Description
id String Unique identifier (UUID) for this error occurrence
status String HTTP status code as a string (e.g., "404")
code String Application-specific error code (e.g., "NOT_FOUND")
detail String Human-readable explanation of the error
source Object Points to the error source — contains pointer, parameter, or header
title String Short summary of the error (optional)
links Object Links related to the error (optional)
meta Object Additional metadata (optional)

Built-in Exception Handling

JsonApi4j registers one error handler factory by default.

DefaultErrorHandlerFactory

Covers all framework-specific exceptions from the core and REST layers, as well as user-facing exceptions from the pro.api4.jsonapi4j.exception package. The registry matches the most specific exception class first — subclass handlers take priority over the JsonApi4jException catch-all.

Exception HTTP Status Error Code When It Occurs
JsonApiRequestValidationException From exception From exception Single validation failure — produces one error object. Normally 400; see Answering with a different status
CompositeJsonApiRequestValidationException 400 From errors Multiple validation failures collected by JsonApiRequestValidator — produces multiple error objects in one response
ResourceNotFoundException 404 NOT_FOUND Resource with the given ID does not exist
JsonApi4jException From exception From exception Catch-all for exceptions that extend JsonApi4jException — uses the exception’s own httpStatus and errorCode
DataRetrievalException 502 BAD_GATEWAY Downstream service failed to return data
MappingException 500 INTERNAL_SERVER_ERROR DTO-to-JSON:API object failure
OperationNotFoundException 404 NOT_FOUND Requested operation is not implemented for this resource

Collect-All-Errors Validation

When using JsonApiRequestValidator.forRequest(request), the validator runs all configured validators (path, parameters, headers, body) and collects errors rather than stopping at the first failure. If multiple validators fail, the response contains all errors at once:

{
  "errors": [
    {
      "id": "...",
      "status": "400",
      "code": "VALUE_IS_ABSENT",
      "detail": "value can't be null",
      "source": { "pointer": "/data/attributes" }
    },
    {
      "id": "...",
      "status": "400",
      "code": "INVALID_ENUM_VALUE",
      "detail": "'wrong' value is not allowed, available values: [countries]",
      "source": { "pointer": "/data/relationships/citizenships/data/0/type" }
    }
  ]
}

Each developer-provided validator lambda is atomic — if a lambda throws, the error is collected and the next validator runs. Errors within a single lambda are still fail-fast (e.g., a null check followed by a method call on the same value). This design prevents NPEs from interdependent checks while still collecting errors across independent validators.

Answering with a different status

Validation failures are 400 by default. A few are not: JSON:API requires 409 Conflict when a request body is aimed at the wrong collection, and 403 Forbidden when a create request supplies its own id and the server does not accept client-generated ids. withHttpStatus says so on the assertion itself:

.withResourceTypeValidator(type -> type
        .isNotBlank()
        .withHttpStatus(HttpStatusCodes.SC_409_CONFLICT.getCode())
        .withErrorCode(DefaultErrorCodes.CONFLICT)
        .withDetail("resource type does not belong to this collection")
        .isEqualTo(request.getTargetResourceType().getType()))

Both built-in cases above are already enforced for you — this is how, and the same mechanism is available to your own validators when a failure needs a status of its own, such as 409 for a duplicate.

Such a failure is reported alone. Collecting exists to tell a client everything that is wrong at once, which works only while the errors share a status — a JSON:API document carries many error objects but one HTTP status. A 409 merged into a batch of 400s would have to be answered 400, breaking the rule that asked for 409 in the first place. So a failure carrying its own status short-circuits: it is returned by itself, and anything collected before it is dropped.

The consequence is worth stating plainly. A request that is both aimed at the wrong collection and has four malformed fields answers 409 describing only the first problem. The client fixes it, resubmits, and then learns about the other four.

The override applies to the assertion that follows it, exactly like withErrorCode and withDetail, and is cleared once that assertion has run. Order matters:

type.isNotBlank().withHttpStatus(409).isEqualTo(expected);   // 409 on the equality check
type.withHttpStatus(409).isNotBlank().isEqualTo(expected);   // 409 on isNotBlank, then cleared

Error Codes

Error codes are represented by the ErrorCode interface (single method: toCode()). The framework provides DefaultErrorCodes with 32 built-in codes organized by category:

Request validation: GENERIC_REQUEST_ERROR, MISSING_REQUIRED_PARAMETER, MISSING_REQUIRED_HEADER, INVALID_ENUM_VALUE, VALUE_IS_ABSENT, VALUE_EMPTY, VALUE_TOO_SHORT, VALUE_TOO_LONG, VALUE_TOO_HIGH, VALUE_TOO_LOW, VALUE_INVALID_FORMAT, ARRAY_LENGTH_TOO_SHORT, ARRAY_LENGTH_TOO_LONG, CONFLICTING_PARAMETERS, INVALID_CURSOR, INVALID_LIMIT, INVALID_PAYLOAD, UNSUPPORTED_INCLUDE

HTTP/server: NOT_FOUND, METHOD_NOT_SUPPORTED, NOT_ACCEPTABLE, UNSUPPORTED_MEDIA_TYPE, CONFLICT, CLIENT_GENERATED_ID_NOT_SUPPORTED, BAD_GATEWAY, INTERNAL_SERVER_ERROR, SERVICE_UNAVAILABLE, MAX_AMOUNT_OF_RESOURCES

Authentication/authorization: UNAUTHORIZED, ACCESS_TOKEN_REVOKED, ACCESS_TOKEN_EXPIRED, FORBIDDEN, INSUFFICIENT_SCOPES, INSUFFICIENT_ENTITLEMENTS

You can define your own error codes by implementing ErrorCode:

public enum MyErrorCodes implements ErrorCode {

    DUPLICATE_EMAIL,
    ACCOUNT_SUSPENDED,
    QUOTA_EXCEEDED;

    @Override
    public String toCode() {
        return name();
    }
}

Custom Error Handlers

To handle your own exceptions, implement ErrorHandlerFactory and register it as a bean. The framework auto-discovers custom factories and adds them to the registry alongside the built-in ones. The error-handling API — ErrorHandlerFactory, ErrorsDocSupplier, ErrorHandlerFactoriesRegistry, JsonApi4jErrorHandlerFactoriesRegistry and the ErrorsDocFactory helpers — lives in pro.api4.jsonapi4j.errorhandling, with DefaultErrorHandlerFactory in pro.api4.jsonapi4j.errorhandling.impl (module jsonapi4j-base).

1. Define Your Exception

public class DuplicateEmailException extends RuntimeException {

    private final String email;

    public DuplicateEmailException(String email) {
        super("Email already registered: " + email);
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

2. Create an ErrorHandlerFactory

public class MyErrorHandlerFactory implements ErrorHandlerFactory {

    @Override
    public Map<Class<? extends Throwable>, ErrorsDocSupplier<?>> getErrorResponseMappers() {
        return Map.of(
            DuplicateEmailException.class, new ErrorsDocSupplier<DuplicateEmailException>() {
                @Override
                public ErrorsDoc getErrorResponse(DuplicateEmailException ex) {
                    return ErrorsDocFactory.conflictErrorsDoc(
                        "Email " + ex.getEmail() + " is already registered"
                    );
                }

                @Override
                public int getHttpStatus(DuplicateEmailException ex) {
                    return 409;
                }
            }
        );
    }
}

ErrorsDocFactory provides convenience methods for common HTTP statuses: badRequestErrorsDoc(), resourceNotFoundErrorsDoc(), conflictErrorsDoc(), badGatewayErrorsDoc(), internalServerErrorsDoc(), unsupportedMediaTypeErrorsDoc(), notAcceptableErrorsDoc(), methodNotSupportedErrorsDoc(), and the generic genericErrorsDoc(status, code, detail).

3. Register It

Define the factory as a Spring bean. The framework auto-discovers all ErrorHandlerFactory beans via ObjectProvider.

@Configuration
public class ErrorConfig {

    @Bean
    public ErrorHandlerFactory myErrorHandlerFactory() {
        return new MyErrorHandlerFactory();
    }
}

Provide the factory as a CDI bean. The framework discovers all ErrorHandlerFactory instances via Instance<ErrorHandlerFactory>.

public class ErrorConfig {

    @Produces
    @Singleton
    public ErrorHandlerFactory myErrorHandlerFactory() {
        return new MyErrorHandlerFactory();
    }
}

Register the factory on the ErrorHandlerFactoriesRegistry before the framework initializes, or set it as a ServletContext attribute.