render does not take effect when Larave develops Dingo to handle custom Exception s [Solution]

Posted by quintin on Tue, 08 Oct 2019 17:53:00 +0200

1. The way to use Dingo Api to customize Exception is

First, define Exception classes, such as AppExceptions ApiException

namespace App\Exceptions;

use Exception;
use Throwable;

class ApiException extends Exception
{
    public function __construct(string $message = "", int $code = 1, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}   
     

Second, in AppExceptions Handler for Exception processing

public function render($request, Exception $exception)

{
    if ($exception instanceof ApiException) {
        return response()->json(['status'=>$exception->getCode(), 'msg'=> $exception->getMessage()]);//Custom Return
    }

    return parent::render($request, $exception);
}

Finally, throw new ApiException('request error', 123) when used.

2. When using Dingo api to process interfaces, we found that laravel itself could not catch exceptions in appExceptions Handler and render could not take effect because Dingo took over Exception and solved the following problems

First, redefine a Handler class

namespace App\Exceptions;

use Exception;
use Dingo\Api\Exception\Handler as DingoHandler;

class ApiHandler extends DingoHandler
{
    public function handle(Exception $exception)
    {
        if ($exception instanceof ApiException) {
            return ['status'=>$exception->getCode(), 'msg'=> $exception->getMessage()];//Custom return. Note that response() can't be used here, because Dingo encapsulation is processed, all when code returns to 500, so you should return array directly here.

        }
        return parent::handle($exception);
    }
}

Next, register the processing class, which can be added directly to the AppProviders AppService Provider - > boot function (this method is used in this case), or customize a Provider, which can be added to the providers array of config/app.php.

    public function boot()
    {
        // Custom error handling
        $this->app->alias('api.exception', 'App\Exceptions\ApiHandler');

        $this->app->singleton('api.exception', function ($app) {
            return new \App\Exceptions\ApiHandler($app['Illuminate\Contracts\Debug\ExceptionHandler'],
                $app['config']['api.errorFormat'], $app['config']['api.debug']);
        });
    }

Finally, throw new ApiException('request error', 123) when used.

Topics: PHP JSON Laravel