Errors & content negotiation
Error documents
One line in bootstrap/app.php renders the exceptions as JSON:API error documents, for the requests that expect JSON:
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.
| Exception | Status | Error objects |
|---|---|---|
ValidationException | its status (422) | one per message, with source.pointer (/data/attributes/title) or source.parameter (fields[post]) |
AuthenticationException | 401 | its message |
AuthorizationException | 403, or the status of denyWithStatus() / denyAsNotFound() | its message |
ModelNotFoundException | 404 | no detail: the class of the model is not disclosed |
HttpException (abort()) | its status, with its headers | its message |
| any other | 500 | its 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.
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:
'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:
Route::middleware('jsonapi')->group(function () {
Route::apiResource('posts', PostController::class);
});
415 Unsupported Media Typewhen theContent-Typeisapplication/vnd.api+jsonwith a parameter other thanextandprofile, or with an extension the server does not support;406 Not Acceptablewhen everyapplication/vnd.api+jsonofAccepthas such a parameter or extension, or is refused (q=0);*/*andapplication/jsonare 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.
jsonapi middleware alias keeps it: alias
Ark4ne\JsonApi\Http\Middleware\NegotiateContent under another name.