ffegu / laravel-api-error-handler
处理API错误的包
v2.1
2021-05-05 12:11 UTC
Requires
- illuminate/support: ~6|~7|~8
Requires (Dev)
- phpunit/phpunit: ^8.5
README
一个用于处理API开发中异常的有用包
📥 安装
您可以通过Composer安装此包
composer require ffegu/laravel-api-error-handler
安装后,您可以使用以下命令发布配置文件
php artisan vendor:publish --tag laravel-api-error-handler
⚙️ 配置
要配置此包,请转到 config/api-error-handler.php
<?php return [ "Symfony\Component\HttpKernel\Exception\NotFoundHttpException" => "\hamidreza2005\LaravelApiErrorHandler\Exceptions\NotFoundException", "ErrorException" => "\hamidreza2005\LaravelApiErrorHandler\Exceptions\ServerInternalException", "Illuminate\Database\QueryException" => "\hamidreza2005\LaravelApiErrorHandler\Exceptions\ServerInternalException", "Illuminate\Auth\AuthenticationException" => "\hamidreza2005\LaravelApiErrorHandler\Exceptions\AccessDeniedException", "Symfony\Component\HttpKernel\Exception\HttpException" => "\hamidreza2005\LaravelApiErrorHandler\Exceptions\AccessDeniedException", "Illuminate\Validation\ValidationException" => "\hamidreza2005\LaravelApiErrorHandler\Exceptions\ValidationException", "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException"=>"\hamidreza2005\LaravelApiErrorHandler\Exceptions\NotFoundException", ];
此包提供一些常见异常,如 ModelNotFound
。但若要自定义它,您可以这样操作
<?php return [ "Your Error Namespace" => "the class that handle this error", ];
🚀 让此包获取您的错误
转到 app\Exceptions\Handler.php
并放置以下代码
<?php namespace App\Exceptions; use hamidreza2005\LaravelApiErrorHandler\Traits\ApiErrorHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; class Handler extends ExceptionHandler { use ApiErrorHandler; /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. * * @return void */ public function register() { // } public function render($request, Throwable $e) { return $this->handleError($this->prepareException($e)); } }
创建您自己的错误处理器!
如果您想创建一个自定义处理器而不是使用默认处理器,您可以在任何位置创建一个类(但您的类必须扩展 hamidreza2005\LaravelApiErrorHandler\Exceptions\ExceptionAbstract
)
例如
<?php namespace myNamespace; class MyException extends ExceptionAbstract { public function handleStatusCode():void { $this->statusCode = 2018; } public function handleMessage():void { $this->message = "My Message"; } }
您可以在 config/api-error-handler.php
中这样做
<?php return [ "ErrorException" => "myNamespace\MyException" ];
❗ 注意
如果出现未知异常,此包会自动在响应中显示它,但如果您不想这样做,可以在 .env
中将 APP_DEBUG
设置为 false
。当 APP_DEBUG
为 false
时,服务器内部错误将在响应中显示
📜 许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件
🙋 贡献
如果您发现了一个问题或有一个更好的方法来做某事,请随时打开一个issue或pull request。