tp5自定义异常处理

本文介绍了在ThinkPHP5框架中如何自定义异常处理。首先,通过定义Model层和Controller层的异常信息,然后创建全局异常处理类。接着,详细讲解了自定义异常类的构建,包括设置常量、定义验证错误信息以及实现Handle类进行异常验证和渲染。最后,通过实例演示了如何使用render方法并结合instanceof检查来捕获和处理自定义异常。

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

1.传统模式自定义异常处理

定义model层分母为0的异常信息

# url /api/model/Index.php


namespace app\api\model;


use think\Exception;

class Index
{
    public static function getIndexID($id)
    {
        try{
            1/0;
        }
        catch (Exception $ex)
        {
            // TODO: 可以记录日志
            throw $ex;
        }
        return true;
    }
}

定义controller层index信息

<?php


namespace app\api\controller;


use app\api\validata\IDMustBePostiveInt;
use app\api\model\Index as IndexModel;
use think\Exception;

class Index
{
   
    public function getindex($id)
    {
        try
        {
            $index = IndexModel::getIndexID($id);
        }
        catch (Exception $ex)
        {
            $err = [
                'error_code' => 10001,
                'msg' => $ex->getMessage()
            ];
            return json($err,400);
        }
        return $index;
    }

全局异常处理类

        1.定义exception下常员变量信息继承与Exception

<?php


namespace app\lib\exception;


use think\Exception;

class BaseException extends Exception
{
    // HTTP 状态码 404,200
    public $code;
    // 错误具体信息
    public $msg;
    // 自定义错误码
    public $errorCode;

}

         2. 定义需验证的成员错误信息

<?php


namespace app\lib\exception;


class BannerMissException extends BaseException
{
    public $code = 404;
    public $msg = '请求的banner不存在';
    public $errorCode = 40000;
}

3. 定义 ExceptionHandle类继承与Handle验证

<?php


namespace app\lib\exception;


use Exception;
use think\exception\Handle;
use think\facade\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    public function render(Exception $e)
    {
        if ($e instanceof BaseException){
            // 如果是自定义的异常
            $this ->code = $e->code;
            $this ->msg = $e -> msg;
            $this -> errorCode = $e ->errorCode;
        }else{
            $this ->code = 500;
            $this ->msg = '服务器内部错误';
            $this -> errorCode = 999;
        }
        $request = Request::instance();
        $result = [
            'msg' => $this -> msg,
            'errorCode' => $this ->errorCode,
            'request_url' => $request -> url()
        ];
        return json($result,$this ->code);
    }
}

       使用render方法验证并通过instanceof函数验证是否是自定义异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值