Skip to content

Errors ​

Every error from a route matching api.errors.paths is a JSON:API error document, with the application/vnd.api+json content type:

json
{
  "errors": [
    {
      "status": "422",
      "code": "validation_failed",
      "title": "Validation failed",
      "detail": "This field is required.",
      "source": { "pointer": "/data/attributes/total" },
      "meta": { "request_id": "req_01m8rhxf74d0k224q50r19zkze" }
    }
  ]
}
MemberWhat it is
statusThe HTTP status, as a string.
codeA stable, machine-readable code. Clients branch on it, never on the text.
titleA short summary that is the same for every error with this code.
detailWhat went wrong this time, for people.
sourceWhat caused it: pointer to a member of the request body, parameter for a query parameter such as filter[status], or header.
meta.request_idThe request's ID, also in the X-Request-Id header and the logs.
linksOptional, such as an about link to an upgrade guide.

How exceptions are rendered ​

ExceptionStatusCode
ApiExceptionIts ownIts own
ValidationException, such as from a form request422validation_failed, one error per message, each with its source
AuthenticationException401unauthenticated
AuthorizationException, such as from a policy403forbidden
ModelNotFoundException, such as from route model binding404not_found
Any other HTTP exception, such as abort(409)Its ownThe code for the status, or http_error
Anything else500server_error

A 500 says only "An unexpected error occurred." In the local environment its meta.debug also has the exception, message, file, line and trace. Validation messages are generic, such as "This field is required.", so they never repeat what the client sent.

Built-in error codes ​

These are the cases of FusionStack\Laravel\Errors\ApiErrorCode.

CodeStatusWhen
bad_request400The request is malformed, such as an abort(400).
invalid_api_version400The Api-Version header is not a known, released version. meta.latest_version names the newest.
invalid_include400include names a relationship the endpoint does not allow, or is nested too deeply.
invalid_fieldset400A fields parameter names a type or field the endpoint does not allow.
invalid_filter400A filter names a field or operator the endpoint does not allow.
invalid_sort400sort names a field the endpoint cannot sort by.
invalid_page400A page parameter is invalid, such as a size over the maximum or a cursor from another sort.
invalid_idempotency_key400The Idempotency-Key header is empty or too long.
http_errorAnyAn HTTP error without a more specific code.
unauthenticated401No credentials were sent, or they are invalid or revoked.
forbidden403The credentials are valid, but do not allow this request, such as a policy refusing it.
insufficient_scope403The client lacks a scope the endpoint requires. meta.required_scope names it.
not_found404The resource or route does not exist, or is not visible to this client.
method_not_allowed405The route does not accept this HTTP method.
conflict409The request conflicts with the resource's current state.
idempotency_in_progress409A request with this Idempotency-Key is still running. Retry once it finishes.
api_version_retired410The requested version is retired.
api_version_brownout410The requested version is deprecated, and briefly switched off as a warning before its sunset. Retry-After says when it returns.
endpoint_unavailable_for_version410The endpoint cannot serve the requested version. Use a newer one for it.
validation_failed422The request body failed validation. Each error points at the field at fault.
idempotency_key_mismatch422The Idempotency-Key was already used for a different request.
rate_limited429Too many requests. Wait for the seconds in Retry-After.
server_error500An unexpected server error. Quote the request ID when reporting it.
service_unavailable503The API is temporarily unavailable, such as during maintenance.

ApiException ​

Throw FusionStack\Laravel\Errors\ApiException for an error of your own, such as a business rule:

php
use FusionStack\Laravel\Errors\ApiException;

throw new ApiException(
    ErrorCode::OrderNotPaid,
    "Order {$order->id} is {$order->status}: only paid and shipped orders have an invoice.",
    pointer: '/data/relationships/order/data/id',
);
ArgumentDefaultWhat it is
errorCoderequiredAn ErrorCode case, yours or the package's.
detailThe code's titleWhat went wrong this time.
statusThe code's statusThe HTTP status.
pointernoneThe body member at fault, such as /data/attributes/total.
parameternoneThe query parameter at fault, such as filter[status].
headernoneThe header at fault, such as Idempotency-Key.
meta[]Extra machine-readable details.
links[]Links, such as ['about' => 'https://…'].
headers[]Response headers, such as Retry-After.
previousnoneThe exception that caused it, for the logs.

Your own error codes ​

Define your codes as a string-backed enum implementing FusionStack\Laravel\Errors\ErrorCode, with a status and a title for each:

php
use FusionStack\Laravel\Errors\ErrorCode as Contract;
use FusionStack\Laravel\OpenApi\Description;

enum ErrorCode: string implements Contract
{
    #[Description('Only paid and shipped orders have an invoice to send.')]
    case OrderNotPaid = 'order_not_paid';

    public function status(): int
    {
        return match ($this) {
            self::OrderNotPaid => 409,
        };
    }

    public function title(): string
    {
        return match ($this) {
            self::OrderNotPaid => 'Order not paid',
        };
    }
}

List the enum in api.openapi.error_codes, and the API reference documents each code with its #[Description]. api:docs:lint reports codes without one. The starter kit has one at app/Api/ErrorCode.php.

Released under the MIT License.