hamidreza2005/laravel-api-error-handler

v2.1.0 2023-10-13 14:47 UTC

This package is auto-updated.

Last update: 2024-09-13 16:59:41 UTC


README

这是一个用于处理Laravel中异常的有用包。

📥 安装

您可以通过Composer安装此包

composer require hamidreza2005/laravel-api-error-handler

安装后,您可以使用以下命令发布配置文件

php artisan vendor:publish --tag laravel-api-error-handler

⚙️ 配置

要配置此包,请转到 config/api-error-handler.php

<?php  
  
return [  
    /*
     * this is where you define which handler deal with which errors. each handler can handle multiple errors
     */

    "handlers" =>[
        NotFoundExceptionHandler::class => [
            "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
            "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException"
        ],
        ServerInternalExceptionHandler::class => [
            "ErrorException",
            "Illuminate\Database\QueryException"
        ],
        AccessDeniedExceptionHandler::class => [
            "Illuminate\Auth\AuthenticationException",
            "Symfony\Component\HttpKernel\Exception\HttpException"
        ],
        ValidationExceptionHandler::class => [
            "Illuminate\Validation\ValidationException"
        ],
    ],

    /*
     * if the app is not in debug mode. all unknown exceptions will be handled by this.
     */
    "internal_error_handler" => ServerInternalExceptionHandler::class,
];

此包提供了一些常见异常(如ModelNotFound)的处理程序。但如果您想自定义它,可以这样做

<?php  
  
return [  
  YourHandler::class => [
        // exceptions
    ],   
];

🚀 如何让处理程序执行其工作?

ApiErrorHandler 特性添加到位于 app\Exceptions\Handler.phpExceptionHandler

<?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->handle($this->prepareException($e));  
	 }
 }

创建您自己的异常处理程序!

如果您想创建自己的处理程序,则您的类必须扩展 hamidreza2005\LaravelApiErrorHandler\Handlers\ExceptionHandler

例如

<?php  

class MyException extends ExceptionHandler  
{  
	  public function handleStatusCode():void  
	  {  
		  $this->statusCode = 499;  
	  }
	   
	  public function handleMessage():void  
	  {  
		  $this->message = "My Message";  
	  }
 }

📜 许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。

🙋 贡献

如果您发现问题,或有一个更好的方法来做某事,请随时提交问题或拉取请求。