tp5中捕获异常的配置

首选在配置文件中加入配置如下

    // 异常处理handle类 留空使用 \think\exception\Handle
    'exception_handle'       => '\\app\\common\\exception\\Http',
    'http_exception_template'    =>  [
        // 定义404错误的重定向页面地址
        404 =>  APP_PATH.'view/error/404.html',
    ],

值得注意的是该配置文件必须是所有模块的而不是单个的模块的

目录结构图如下

 

然后在\app\common\exception\Http.php文件中加入以下代码:

<?php
namespace app\common\exception;


use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\Response;
class Http extends Handle
{


    public function render(Exception $e)
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }


        // 请求异常
        if ($e instanceof HttpException && request()->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }


        //TODO::开发者对异常的操作
        if($e->getStatusCode()=='404'){
            return response($e->getMessage(), $e->getStatusCode());
        }
        //可以在此交由系统处理
        return parent::render($e);
    }


}

然后就可以在编码中捕捉异常了

try{
Db::name('user')->find();
}catch(\Exception $e){
$this->error('执行错误');
}
$this->success('执行成功!');

---------------------
作者:司徒小子
来源:CSDN
原文:https://blog.csdn.net/ruoshui1748/article/details/78032733/
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/ariclee/p/10474414.html