Skip to main content

Errors

An API that answers its errors in a shape of its own makes every client learn that shape. The package answers every failure of an API request as JSON:API error objects (JSON:API 1.1, Errors), served as application/vnd.api+json:

{
"errors": [
{
"status": "404",
"code": "not_found",
"title": "Not found",
"detail": "The requested resource does not exist.",
"meta": {
"request_id": "019a9c9e-4d39-74db-a2f5-b0c1d2e3f405"
}
}
]
}

Every status, code, title and detail comes from one error catalog that the package carries, a copy of errors/codes.json, the file the Frontline gateway answers from. An error the gateway answers and the same error from Laravel are the same response: the same status, the same headers and the same bytes, apart from the request id.

Which requests get errors​

A failure is answered with JSON:API errors when the request

  • goes to the API host: api. before the host of app.url, so an application at example.com answers its API at api.example.com. HTTP_API_HOST names another host;
  • goes to a host in http-api.errors.hosts, or under a prefix in http-api.errors.route_prefixes. The package ships no prefix;
  • asks for application/vnd.api+json in its Accept header.

Every other request is answered as Laravel answers it, so a page stays a page, and a request that expects JSON outside the API keeps Laravel's JSON with its message. Setting http-api.errors.when_json_is_expected to true answers such a request with JSON:API errors as well, outside the API too.

An application that knows its API better, by a path or a middleware of its own, binds its own RecognizesApiRequests. The class goes into app/Http/ApiRequests.php:

namespace App\Http;

use Illuminate\Http\Request;
use Pushery\HttpApi\Errors\RecognizesApiRequests;

final class ApiRequests implements RecognizesApiRequests
{
public function isApiRequest(Request $request): bool
{
return $request->is('v1', 'v1/*');
}
}

The binding goes into the register method of a service provider:

use App\Http\ApiRequests;
use Pushery\HttpApi\Errors\RecognizesApiRequests;

$this->app->bind(RecognizesApiRequests::class, ApiRequests::class);

The error object​

MemberContent
statusthe HTTP status, as a string
codestable, for programs: not_found, validation_failed
titleshort, the same for every error of the code
detailsays what to do
sourcethe input that caused the error: pointer for a member of the body, parameter for a query parameter, header for a header
metarequest_id, the id of the request

The members come in this order, without whitespace. The title and the detail are English and come from the catalog, never from the message of an exception: abort(403, 'Exports are not part of this plan.') answers with the catalog's detail for forbidden, and the message of a missing model, which names its class and its key, never reaches a client.

The response carries Content-Type: application/vnd.api+json, Cache-Control: no-store, private, the request id in Request-Id, and the headers its code names, such as WWW-Authenticate: Bearer for a 401. It carries no other header, with two exceptions: a throttled request keeps its limit headers, and the maintenance mode keeps its Retry-After when the end is known.

Behind the gateway, the request id is the one the gateway assigned and sent along as Frontline-Request-Id, so the client, the gateway's log and the application's error name the same request. Without the gateway, each request gets a new UUID of version 7.

The codes​

The codes Laravel answers with:

StatusCodeTitleAnswers
400malformed_requestMalformed requestabort(400), a missing or malformed Idempotency-Key, a page parameter a list cannot take, and a filter, sort, include, field or append its route does not declare
401unauthenticatedUnauthenticatedan AuthenticationException
403forbiddenForbiddena refused authorization, and abort(403)
404not_foundNot founda missing route or model, and a known path asked with another method
406not_acceptableNot acceptablean Accept header that admits no JSON:API answer
409conflictConflicta request under an Idempotency-Key whose answer was not kept
409request_in_flightRequest in flighta request under an Idempotency-Key whose first request still runs, with Retry-After
412precondition_failedPrecondition failedabort(412)
413payload_too_largePayload too largea body larger than PHP takes
415unsupported_media_typeUnsupported media typea body that is no JSON:API
422validation_failedValidation faileda failed validation, and an Idempotency-Key sent with another request
428precondition_requiredPrecondition requiredabort(428)
429rate_limitedToo many requeststhe throttle middleware
500internal_errorInternal errorevery other failure, and a status the catalog has no code for
503maintenanceUnder maintenancethe maintenance mode

The gateway answers further codes of its own, such as request_timeout and backend_unavailable. The catalog in the package lists every one of them.

How a failure is answered​

  • A failed validation is one error per invalid field. A member of the body is named by its JSON pointer: the field data.attributes.title is /data/attributes/title. A field the query carries and the body does not is named by its parameter, filter[status], and so is every field of a GET. Laravel's message for the field does not reach the client: the detail of validation_failed tells it to read source.
  • A missing route, a missing model and a known path asked with another method answer the same 404. A 405 would list the methods of a path to anyone who asks, and the gateway in front never answers one.
  • A throttled request names its wait in Retry-After and in the detail.
  • An exception nobody anticipated answers 500 internal_error, and it reaches the reporters like every other. With app.debug on, Laravel's debug answer stays, which is what a developer wants to read.
  • An exception that carries its own response, an HttpResponseException or a validation given one, keeps that response.

Content negotiation​

NegotiateJsonApi holds a route to the content negotiation of JSON:API 1.1. It goes on the routes that speak JSON:API, in routes/api.php:

use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;
use Pushery\HttpApi\Errors\NegotiateJsonApi;

Route::post('/articles', [ArticleController::class, 'store'])
->middleware(['auth:sanctum', NegotiateJsonApi::class]);

A request body comes as application/vnd.api+json. One in another media type, one with a media type parameter other than profile, and one that asks for an extension through ext is refused with 415 unsupported_media_type, because the package supports no extension. An Accept header that admits no JSON:API answer is refused with 406 not_acceptable: it names the media type, and every time with another parameter or with an extension, or it names neither the media type nor a range that covers it. A request without Accept takes any answer.

An error of your own​

An exception that implements ProvidesErrorDocument answers with the errors it names, made from the catalog with JsonApiError::of(), so a code the catalog does not have cannot be answered. The class goes into app/Exceptions/OutOfStock.php:

namespace App\Exceptions;

use Pushery\HttpApi\Errors\ErrorDocument;
use Pushery\HttpApi\Errors\JsonApiError;
use Pushery\HttpApi\Errors\ProvidesErrorDocument;
use RuntimeException;

final class OutOfStock extends RuntimeException implements ProvidesErrorDocument
{
public function toErrorDocument(): ErrorDocument
{
return ErrorDocument::of(JsonApiError::of('conflict', source: ['pointer' => '/data/attributes/quantity']));
}
}

A code with more than one detail takes the name of the detail to answer with, and the values of its placeholders: JsonApiError::of('rate_limited', 'key', ['limit' => '120', 'window' => 'minute', 'retry_after' => '12']) answers "This key is limited to 120 requests per minute. Retry after 12 seconds."

Switching it off​

HTTP_API_ERRORS=false leaves every failure to Laravel, and HTTP_API_ENABLED=false switches the whole package off. With the errors alone switched off, the idempotency middleware still answers its refusals as JSON:API errors.

Upgrading from 0.3​

  • Configuration: the section problems is errors. type_base and www_authenticate are gone, and when_json_is_expected ships false. HTTP_API_PROBLEMS is HTTP_API_ERRORS, and HTTP_API_PROBLEM_TYPE_BASE is gone. A published config/http-api.php is published again or edited by hand.
  • Classes: ProvidesProblem is ProvidesErrorDocument, which returns an ErrorDocument of errors made from the catalog. Problem, ProblemRenderer, NamesProblems and CatalogLanguage are gone, because the catalog decides every code, title and detail. RecognizesApiRequests and ConfiguredApiRequests moved to Pushery\HttpApi\Errors.
  • Translations: the package ships no catalogs, and the tag http-api-lang publishes nothing. The translations an application published for the package can go.
  • Clients: an error is {"errors": [...]} in application/vnd.api+json, and a client branches on code instead of type. A refused idempotency key answers with its code and names the header in source.header, and a key the store does not take answers 500 internal_error instead of 503.