【TP5 :错误和调试】异常处理

版权声明:本文为ywcmoon原创文章,未经允许不得转载。 https://blog.csdn.net/qq_39251267/article/details/82496506

异常处理


默认异常处理

在调试模式下,系统默认展示的错误页面:
这里写图片描述

在部署模式下面,显示简单的提示文字:

// 错误显示信息,非调试模式有效
'error_message'          => '页面错误!请稍后再试~',

这里写图片描述

5.0版本默认对任何错误(包括警告错误)抛出异常,可在应用公共函数文件中或者配置文件中使用error_reporting方法设置错误报错级别(在入口文件中设置是无效的),例:

// 异常错误报错级别,
error_reporting(E_ERROR | E_PARSE );

异常处理接管

框架支持异常页面由开发者自定义类进行处理,需要配置参数exception_handle

    // 异常处理handle类 留空使用 \think\exception\Handle
    'exception_handle'       => '\\app\\common\\exception\\Http',

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

<?php
namespace app\common\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
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::开发者对异常的操作
        //可以在此交由系统处理
        return parent::render($e);
    }

}

注意:如果配置了exception_handle,且没有再次调用系统render的情况下,配置http_exception_template就不再生效,具体可以参考Handle类内实现的功能。

V5.0.11版本开始,可通过闭包定义的方式简化异常自定义处理。例如,上面的自定义异常类可以改为直接配置exception_handle参数:

'exception_handle'  =>  function(Exception $e){
    // 参数验证错误
    if ($e instanceof \think\exception\ValidateException) {
        return json($e->getError(), 422);
    }

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

部署模式异常

关闭调试模式,发生错误后不会提示具体的错误信息,如果你仍然希望看到具体的错误信息,那么可以如下设置:

// 显示错误信息
'show_error_msg'        =>  true,    

这里写图片描述


异常捕获

可使用PHP的异常捕获进行必要的处理,但在异常捕获中不要使用think\Controller类的errorsuccessredirect方法,因为上述三个方法会抛出HttpResponseException异常,从而影响正常的异常捕获,例:

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

猜你喜欢

转载自blog.csdn.net/qq_39251267/article/details/82496506