ThinkPHP6 封装自定义全局异常错误类

本文介绍如何在PHP项目中自定义异常处理类,包括配置异常处理类、创建异常类及调用方法等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

// 绑定自定义异常处理handle类
    'think\exception\Handle'       => '\app\lib\exception\ExceptionHandler',

创建异常类文件,如:app/lib/exception/ExceptionHandler.php

自定义类需要继承think\exception\Handle并且实现render方法,可以参考如下代码:

<?php


namespace app\lib\exception;

use think\exception\Handle;
use think\Response;
use Throwable;

class ExceptionHandler extends Handle
{
    //定义状态码
    public $code;
    //定义错误信息
    public $message;
    //定义错误码
    public $errorCode;

    public function render($request, Throwable $e):Response
    {
        //判断$e是不是属于BaseException类传来的值
        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->message = $e->message;
            $this->errorCode = $e->errorCode;
        }else{
            //判断如果是调试模式的输出内容
            if(Env::get('APP_DEBUG')){
                return parent::render($request, $e);
            }
            //如果不是则返回特定的信息
            $this->code = 500;
            $this->message = '服务器异常';
            $this->errorCode = '10000';
        }
        $res = [
            'code'=>  $this->code,
            'message'=>$this->message,
            'errorCode'=>$this->errorCode
        ];
        return json($res,$this->code);
    }
}

创建调用类文件,如:app/lib/exception/BaseException.php

<?php


namespace app\lib\exception;
use Exception;

class BaseException extends Exception
{
    //定义状态码
    public $code = 400;
    //定义错误信息
    public $message = '异常信息';
    //定义错误码
    public $errorCode = '999';

    public function __construct($params = []){
//        halt($params);
        //判断传过来的值是否是数组,如果不是则返回
        if(!is_array($params)) return;
        //如果$params传来的有值就修改$this->code的值为传来的值
        if(array_key_exists('code',$params)) $this->code=$params['code'];
        //如果$params传来的有值就修改$this->message的值为传来的值
        if(array_key_exists('message',$params)) $this->message=$params['message'];
        //如果$params传来的有值就修改$this->errorCode的值为传来的值
        if(array_key_exists('errorCode',$params)) $this->errorCode=$params['errorCode'];
//        halt(array_key_exists('code',$params));
    }
}

以上就已经封装好了异常处理类,调用方法如下:

//首先在命名空间下面引入类
use app\lib\exception\BaseException;

//在方法里面我们可以这样调用
throw new BaseException(['code'=>560,'message'=>'异常报错','errorCode'=>10000]);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值