ThinkPHP6项目基操(10.不可预知的內部异常处理)

一、不可预知异常

如果方法里使用未定义的字段:

public function aa(){
    
    
    echo $aa;
}

访问页面就会出错:
在这里插入图片描述

二、解决方案:

1. 修改app目录下的ExceptionHandle.php

修改app目录下的 ExceptionHandle.phprender方法,添加自定义的异常处理:

public function render($request, Throwable $e): Response
{
    
    
    // 添加自定义异常处理机制
    return show(config("status.error"), $e->getMessage());
    // 其他错误交给系统处理
    // return parent::render($request, $e);
}

再访问就返回了我们定义的异常结果了:
在这里插入图片描述

但是直接修改app目录下的配置文件不太好,因为app目录下的都是common文件,会作用于所有的应用,如果我们像上面配置为json格式输出错误,那么如果是模板输出出错也会返回json格式,所以不合理。

2. 不同应用模块配置不同的错误信息格式

下面以API模块举例:

(1) 还原app目录下的ExceptionHandle.php文件;
(2) 在demo应用下新建exception文件夹(与controller同级),新建Http.php类,仿造ExceptionHandle继承Handle类,重写render方法:
在这里插入图片描述

Http.php:

<?php

namespace app\demo\exception;

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

class Http extends Handle
{
    
    
    public $httpStatus = 500;
    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
    
    
        // 添加自定义异常处理机制
        return show(config("status.error"), $e->getMessage(), [],$this->httpStatus);
    }
}

(3) 然后,复制app目录下的provider.phpdemo应用目录,修改think\exception\Handle配置:

provider.php :

<?php

// 容器Provider定义文件
return [
    'think\exception\Handle' => 'app\\demo\\exception\\Http',
];

以上就是配置api模块的错误信息;如果是后台模板引擎返回报错,可以定义一个自定义错误页面,而不是返回一个json数据。

3. throw异常处理

在控制器加一个方法throw一个think\exception\HttpException异常:

public function aa(){
    
    
    throw new HttpException(404,"找不到相应的数据");
}

访问结果:
在这里插入图片描述
看起来没问题,细心的朋友会发现状态码不太对,我上面抛出的异常设置的状态码是404,这里的请求是500,这是为啥呢?
在这里插入图片描述
原因是上面自定义异常处理类里面重写的render方法里面是自定义的状态码$httpStatus=500

public $httpStatus = 500;
public function render($request, Throwable $e): Response
{
    
    
    // 添加自定义异常处理机制
    return show(config("status.error"), $e->getMessage(), [],$this->httpStatus);
}

我们把这里返回的状态码换为$e->getStatusCode()

return show(config("status.error"), $e->getMessage(), [],$e->getStatusCode());

再访问,状态码已OK:
在这里插入图片描述

但是这里的$e->getStatusCode()只是在throw异常的时候才有这个方法,比如第一步的输出未知变量的错误就没有这个方法,页面就会报错,所以这里需要修改异常处理类:
在这里插入图片描述
修改异常处理类Http.php,这样两种错误异常都可以正常访问了:

public $httpStatus = 500;
public function render($request, Throwable $e): Response
{
    
    
    if(method_exists($e, "getStatusCode")){
    
    
        $httpStatus = $e->getStatusCode();
    }else{
    
    
        $httpStatus = $this->httpStatus;
    }
    // 添加自定义异常处理机制
    return show(config("status.error"), $e->getMessage(), [],$httpStatus);
}

猜你喜欢

转载自blog.csdn.net/zy1281539626/article/details/110457731