-
Notifications
You must be signed in to change notification settings - Fork 0
Configuration
As this package is framework agnostic you will need zero configuration to use as you want.
Otherwise if you are using Laravel/Lumen with Dingo API we provide some configuration that helps you.
The Dingo API package handle all the errors through exceptions and uses an errorFormat
property on its config file that defines the 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 outputed in the JSON API compliant format.
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.