美文网首页ThinkPHP
thinkphp6的自定义异常处理

thinkphp6的自定义异常处理

作者: 这真的是一个帅气的名字 | 来源:发表于2022-02-27 02:16 被阅读0次

    框架支持异常处理由开发者自定义类进行接管,需要在app目录下面的provider.php文件中绑定异常处理类,例如:

    <?php
    use app\ExceptionHandle;
    use app\Request;
    
    // 容器Provider定义文件
    return [
        'think\Request'          => Request::class,
    //    'think\exception\Handle' => ExceptionHandle::class,//原来的异常
        'think\exception\Handle' => '\\app\\exception\\ExecptionHandle'
    ];
    
    

    然后再app下面新建一个exception文件夹放自定义错误信息

    <?php
    /**
     *
     * User: 小贝壳
     * Date: 2022/2/27
     **/
    
    namespace app\exception;
    
    use think\facade\Env;
    use think\exception\Handle;
    use app\exception\HttpExceptions;
    use think\Response;
    use Throwable;
    
    class ExecptionHandle extends Handle
    {
        private $msg = "未知错误";
        private $httpCode = 500;
        private $errorCode = 19999;
    
        public function render($request, Throwable $e): Response
        {
            //判断在`.env`里面是否开始了调试,开启了调试就原样返回,关闭了调试就返回自定义的json格式的错误信息
            if(Env::get("APP_DEBUG") == 1){
                return parent::render($request,$e);
            }
            $this->msg = $e->getMessage() ?: $this->msg;
            //HttpExceptions是继承同级目录下HttpExceptions,代码在下方
            if ($e instanceof HttpExceptions) {
                $this->httpCode = $e->getStatusCode() ?: $this->httpCode;
            }
            $this->errorCode = $e->getCode() ?: $this->errorCode;
            $result_data = [
                'message' => $this->msg,
                'data' => [],
                'code' => $this->errorCode
            ];
            return json($result_data, $this->httpCode);
    
            // 其他错误交给系统处理
            return parent::render($request, $e);
        }
    
    }
    

    同级目录下HttpExceptions 文件

    <?php
    /**
     *
     * User: 小贝壳
     * Date: 2022/2/27
     * Time: 1:42
     **/
    
    namespace app\exception;
    
    use Exception;
    
    class HttpExceptions extends \RuntimeException
    {
        private $statusCode;
        private $headers;
        //主要是重构$code前提,$previous和 $headers在后面方便调用
        public function __construct(int $statusCode, string $message = '', $code = 0, Exception $previous = null, array $headers = [])
        {
            $this->statusCode = $statusCode;
            $this->headers    = $headers;
    
            parent::__construct($message, $code, $previous);
        }
    
        public function getStatusCode()
        {
            return $this->statusCode;
        }
    
        public function getHeaders()
        {
            return $this->headers;
        }
    }
    

    调用

    use app\exception\HttpExceptions;
    throw new HttpExceptions(404,"自定义错误",'444');
    
    

    相关文章

      网友评论

        本文标题:thinkphp6的自定义异常处理

        本文链接:https://www.haomeiwen.com/subject/fsncrrtx.html