Requests

Errors & content negotiation

Render every exception as a JSON:API error document, and apply the content negotiation of JSON:API 1.1.

Error documents

One line in bootstrap/app.php renders the exceptions as JSON:API error documents, for the requests that expect JSON:

bootstrap/app.php
use Ark4ne\JsonApi\Laravel\JsonApi;
use Illuminate\Foundation\Configuration\Exceptions;

->withExceptions(function (Exceptions $exceptions) {
    // Your own render callbacks first: Laravel runs them in order.
    $exceptions->render(
        fn (PaymentRequired $e) => response()->json([...], 402),
    );

    JsonApi::renderErrors($exceptions);
    // or for some requests only:
    // JsonApi::renderErrors(
    //     $exceptions,
    //     fn ($request) => $request->is('api/*'),
    // );
})

The requests rendered are those that expect JSON ($request->expectsJson()), or those the closure accepts. shouldRenderJsonWhen() is not read: give the same condition. An exception that renders itself (render(), Responsable) is still rendered by Laravel.

ExceptionStatusError objects
ValidationExceptionits status (422)one per message, with source.pointer (/data/attributes/title) or source.parameter (fields[post])
AuthenticationException401its message
AuthorizationException403, or the status of denyWithStatus() / denyAsNotFound()its message
ModelNotFoundException404no detail: the class of the model is not disclosed
HttpException (abort())its status, with its headersits message
any other500its message, class, file and line only when app.debug is on
{
  "jsonapi": { "version": "1.1" },
  "errors": [
    {
      "status": "422",
      "title": "Unprocessable Content",
      "detail": "The title field is required.",
      "source": { "pointer": "/data/attributes/title" }
    }
  ]
}

Error renderers of your own

A renderer implements Ark4ne\JsonApi\Http\Errors\ErrorRenderer. Renderers are asked by decreasing PRIORITY; the first that supports the exception renders it.

app/Http/Errors/PaymentRequiredErrorRenderer.php
final readonly class PaymentRequiredErrorRenderer implements ErrorRenderer
{
    // Above the renderers of the package (Validation 400,
    // Authentication / Authorization / ModelNotFound 300, Http 200,
    // Throwable 0).
    public const PRIORITY = 1000;

    public function supports(Throwable $exception): bool
    {
        return $exception instanceof PaymentRequired;
    }

    public function render(
        Throwable $exception,
        Request $request,
    ): ErrorDocument {
        return new ErrorDocument(402, [
            new ErrorObject(
                status: 402,
                title: 'Payment Required',
                detail: $exception->getMessage(),
                code: 'payment',
            ),
        ]);
    }
}

Declare it in config/jsonapi.php; renderers are built by the container, so they may have dependencies:

config/jsonapi.php
'errors' => [
    'renderers' => [App\Http\Errors\PaymentRequiredErrorRenderer::class],
],

To replace them all, bind your own ErrorRenderers in the container (ErrorRenderers::default($jsonapi)->with(...), or new ErrorRenderers($jsonapi, ...$renderers)).

Content negotiation

The jsonapi route middleware applies the content negotiation of JSON:API 1.1:

routes/api.php
Route::middleware('jsonapi')->group(function () {
    Route::apiResource('posts', PostController::class);
});
  • 415 Unsupported Media Type when the Content-Type is application/vnd.api+json with a parameter other than ext and profile, or with an extension the server does not support;
  • 406 Not Acceptable when every application/vnd.api+json of Accept has such a parameter or extension, or is refused (q=0); */* and application/json are served;
  • every response, these errors included, gets Vary: Accept.

The supported extensions are those of document.jsonapi.ext; unknown profiles are ignored. Both errors are HttpExceptions, rendered by JsonApi::renderErrors(). On every route, documents are served with the extensions and profiles of document.jsonapi in their Content-Type.

An application that already has a jsonapi middleware alias keeps it: alias Ark4ne\JsonApi\Http\Middleware\NegotiateContent under another name.