thinkphp8接管异常处理类

创建文件app\Http.php

<?php

declare (strict_types = 1);

namespace app;

use ParseError;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ClassNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\InvalidArgumentException;
use think\exception\RouteNotFoundException;
use think\exception\ValidateException;
use think\facade\Log;
use think\Response;
use Throwable;

class Http extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // 404 - 访问资源不存在
        if (($e instanceof ClassNotFoundException || $e instanceof RouteNotFoundException) || ($e instanceof HttpException && 404 === $e->getStatusCode())) {
            Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getMessage()));
        }
        // 413 - 错误的数据类型或缺失参数
        if ($e instanceof InvalidArgumentException) {
            Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getFile() . '|第' . $e->getLine() . '行|' . $e->getMessage()));
        }
        // 422 - 参数验证错误
        if ($e instanceof ValidateException) {
            Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getError()));
        }
        // 500 - 语法错误
        if ($e instanceof ParseError) {
            Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getFile() . '|第' . $e->getLine() . '行|' . $e->getMessage()));
        }
        // 500 - 数据库错误
        if ($e instanceof PDOException || $e instanceof DbException) {
            Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getFile() . '|第' . $e->getLine() . '行|' . $e->getMessage()));
        }
        // 请求异常
        if ($e instanceof HttpException && $request->isAjax()) {
            Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getStatusCode() . ':' . $e->getMessage()));
        }
        // 其他错误
        Log::error(sprintf('[%s][%s] %s', __CLASS__, __FUNCTION__, $e->getFile() . '|第' . $e->getLine() . '行|' . $e->getMessage()));
    }
}

修改文件app\provider.php

<?php
use app\Http;
use app\Request;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xmode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值