dmn / laravel-exception
Larave 10+的异常处理
v1.0.5
2023-05-12 07:36 UTC
Requires (Dev)
- laravel/framework: ^10.9
- orchestra/testbench: ^8.5
README
composer require dmn/laravel-exception
用法
将Dmn\Exceptions\Handler
扩展到你的app/Exceptions/Handler.php
,并在你的register()
中添加parent::register()
。
<?php namespace App\Exceptions; use Dmn\Exceptions\Handler as ExceptionHandler; use Throwable; class Handler extends ExceptionHandler { ... /** * Register the exception handling callbacks for the application. */ public function register(): void { parent::register(); $this->reportable(function (Throwable $e) { // }); } ... }
要添加更多自定义异常,运行php artisan make:exception
创建新异常,并扩展Dmn\Exceptions\Exception
而不是\Exception
。新异常需要具有$code
、$message
和$httpStatusCode
。你可以添加$description
。
<?php namespace App\Exceptions; use Dmn\Exceptions\Exception; use Illuminate\Http\Response; class NewCustomException extends Exception { protected $code = 'sample_error_code'; protected $message = 'Sample error message'; protected $httpStatusCode = Response::HTTP_BAD_REQUEST; protected $description = 'Sample more detailed error description.'; }
上面的异常将渲染
{ status_code: 400, code: "sample_error_code", message: "Sample error message.", description: "Sample more details error description.", }
要覆盖来自其他包或Laravel本身的异常,你可以在customException()
中添加它。
protected function customException(): void { parent::customException(); // your overrides here // example $this->renderable(function (\Vendor\Package\Exception $e) { throw new App\Exceptions\NewCustomException(); }); }
其他用法选项(不推荐)
你可以直接从你的bootstrap/app.php
使用Dmn\Exceptions\Handler
。
$app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, // App\Exceptions\Handler::class <-- change this Dmn\Exceptions\Handler );