Laravel & Lumen RESTFul API Expansion pack: Dingo API (quad)--Error and exception response

Source: Internet
Author: User
Handling errors while building the API is a pain in the Dingo API, where you don't need to manually build an error response, just throw an inherited from symfony\component\httpkernel\exception\ HttpException the exception, the API will automatically handle this response for you.

The following is a built-in Symfony exception for the Dingo API:

Exception Status Code
Symfony\component\httpkernel\exception\accessdeniedhttpexception 403
Symfony\component\httpkernel\exception\badrequesthttpexception 400
Symfony\component\httpkernel\exception\conflicthttpexception 409
Symfony\component\httpkernel\exception\gonehttpexception 410
Symfony\component\httpkernel\exception\httpexception 500
Symfony\component\httpkernel\exception\lengthrequiredhttpexception 411
Symfony\component\httpkernel\exception\methodnotallowedhttpexception 405
Symfony\component\httpkernel\exception\notacceptablehttpexception 50W
Symfony\component\httpkernel\exception\notfoundhttpexception 404
Symfony\component\httpkernel\exception\preconditionfailedhttpexception 412
Symfony\component\httpkernel\exception\preconditionrequiredhttpexception 428
Symfony\component\httpkernel\exception\serviceunavailablehttpexception 503
Symfony\component\httpkernel\exception\toomanyrequestshttpexception 429
Symfony\component\httpkernel\exception\unauthorizedhttpexception 401
Symfony\component\httpkernel\exception\unsupportedmediatypehttpexception 415

Here is an example that throws a conflicthttpexception exception when we try to update a record that has been updated by someone else:

$api->version (' v1 ', function ($API) {    $api->put (' user/{id} ', function ($id) {        $user = User::find ($id);        if ($user->updated_at > app (' request ')->get (' last_updated ') {            throw new symfony\component\httpkernel\ Exception\conflicthttpexception (' User is updated prior to your request. ');        }        No error, we can continue to update the user as per usual    });

The Dingo API automatically captures the thrown exception and translates it into JSON format, and the HTTP status code of the response changes to match the exception, and the HTTP status code of the conflicthttpexception corresponds to 409, and the default JSON format error message is as follows:

{    "message": "User is updated prior to your request.",    "Status_code": 409}

1. Resource Anomalies

The following is a resource exception, and each exception returns a 422 status code:

dingo\api\exception\deleteresourcefailedexceptiondingo\api\exception\resourceexceptiondingo\api\exception\ Storeresourcefailedexceptiondingo\api\exception\updateresourcefailedexception

What is special about these exceptions is that you can pass validation errors that are encountered when creating, updating, or deleting resources to these exceptions.

Let's take a look at an example of creating a new user validation failure to throw a Storeresourcefailedexception exception:

$api->version (' v1 ', function ($API) {    $api->post (' Users ', function () {        $rules = [            ' username ' = = ['] Required ', ' alpha '],            ' password ' = [' Required ', ' min:7 ']        ;        $payload = App (' request ')->only (' username ', ' password ');        $validator = App (' validator ')->make ($payload, $rules);        if ($validator->fails ()) {            throw new dingo\api\exception\storeresourcefailedexception (' Could not create new User. ', $validator->errors ());        }        Create user as per usual    });

The Dingo API automatically captures the thrown exception and translates it into JSON format, and the HTTP status code of the response changes to a value that matches the exception, and the resource exception returns a 422 status code with the following JSON format error message:

{    "message": "Could not create new user.",    "Status_code": 422,    "errors": {        "username": [            "the Username field is required. "        ],        " password ": [            " The password field is required. "        ]    }}

2. Custom HTTP Exceptions

You can create custom HTTP exceptions if they inherit from symfony\component\httpkernel\exception\httpexception or implement Symfony\component\httpkernel\ Exception\httpexceptioninterface interface.

3. Custom Exception Response

If you need to customize the response returned by the exception, you can register an exception handler:

App (' Dingo\api\exception\handler ')->register (function (symfony\component\httpkernel\exception\ Unauthorizedhttpexception $exception) {    return response::make ([' error ' = ' = ' Hey, what does think you is doing!? ') ], 401);});

Now if the authentication fails we will display the following JSON format information:

{    "error": "Hey, what does think you is doing!?"}

4. Form Request

If you use form requests, you need to inherit the API form request base class or implement your own class. The API request base class checks whether the input request is the request API and, if so, throws a Dingo\api\exception\validationhttpexception exception if the validation fails. This exception is rendered by the Dingo API and returns an error response.

If you want to implement your own form requests, you must overload the Failedvalidation and Failedauthorization methods, which must throw one of these exceptions instead of the HTTP exception that Laravel throws.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.