Skip to content

Configuration

Thieres Tembra edited this page Jun 29, 2016 · 11 revisions

As this package is framework agnostic you will need zero configuration to use as you want.

However if you are using Laravel/Lumen with Dingo API we provide some configuration that helps you.

Dingo API

The Dingo API package handle all the errors through exceptions and uses an errorFormat property on its configuration file that defines the error format.

Configuring error format

To make all your errors a JSON API compliant format we suggest you to configure the errorFormat property like this:

    'errorFormat' => [
        'errors' => [
            [
                'status' => ':status_code',
                'title' => ':title',
                'detail' => ':message',
                'meta' => [
                    'errors' => ':errors',
                    'debug' => ':debug',
                ],
            ]
        ]
    ]

This way every single error on your API will be output in the JSON API compliant format.

Registering a Custom Exception Response

Now we need to customize the response that our exception return, so you need to register a custom error handler.

app('Dingo\Api\Exception\Handler')->register(function (Neomerx\JsonApi\Exceptions\JsonApiException $exception) {
    $encoder = Neomerx\JsonApi\Encoder\Encoder::instance();
    $errors = $exception->getErrors();
    $json = $encoder->encodeErrors($errors);
    $response = new Illuminate\Http\JsonResponse($json, $exception->getHttpCode());

    return Dingo\Api\Http\Response::makeFromJson($response);
});

Once this is done the Dingo API will call this callback every time a Neomerx\JsonApi\Exceptions\JsonApiException is thrown. As this package makes uses of 3rd party neomerx/json-api we also use their exception.

Our callback function gets the instance of Neomerx\JsonApi\Encoder\Encoder and use it to encode the errors to the JSON API compliant format. So we create a new Illuminate\Http\JsonResponse with aproppriate HTTP Status Code. Finally we return a new Dingo\Api\Http\Response from that.

← Installation | Application Error Codes →