3

I am trying to abstract all my error responses to match my API documentation for developing a good, pragmatic API using Lumen and the Dingo API package:

A JSON error body should provide a few things for the developer - a useful error message, a unique error code (that can be looked up for more details in the docs) and possibly a detailed description. JSON output representation for something like this would look like:

{
    "code" : 1234,
    "message" : "Something bad happened :(",
    "description" : "More details about the error here"
}

At the moment, the Dingo API only provides me with the following response:

{
    "message": "Could not create new user.",
    "status_code": 422
}

1. How can I add extra fields to all error responses, e.g "description" and "code"

The configuration page shows a possible error format to set on your bootstrap/app.php file but I'm wondering how I can add possible new tags and use these.

I know it's possible using a custom exception and returning a new response:

app('Dingo\Api\Exception\Handler')->register(function (\App\Exceptions\ValidationException $exception) {
    return Response::make(['code' => $exception->getCode(), 'message' => $exception->getMessage()], 401);
});

I want to know if this is the best practice to do it like this but on all exceptions (including the default ones of Dingo/Symfony), for example using the configuration parameters: ->setErrorFormat([]);

2. Change validation errors format

Validation errors for PUT, PATCH and POST requests will need a field breakdown. This is best modeled by using a fixed top-level error code for validation failures and providing the detailed errors in an additional errors field, like so:

{
    "code" : 1024,
    "message" : "Validation Failed",
    "errors" : [
    {
        "code" : 5432,
        "field" : "first_name",
        "message" : "First name cannot have fancy characters"
    },
    {
        "code" : 5622,
        "field" : "password",
        "message" : "Password cannot be blank"
    }
  ]
}

Currently, Dingo API provides me the JSON in the following format:

{
    "message": "Could not create new user.",
    "status_code": 422,
    "errors": {
        "username": [
            "The username field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}
Verhelst
  • 1,492
  • 2
  • 22
  • 46

0 Answers0