ExceptionHandle.php 3.02 KB
<?php
namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息(日志)的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息(包括日志或者其它方式记录)
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * 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
    {
        $path = strtolower($request->pathinfo());
        if (
            str_starts_with($path, 'admin/') || str_starts_with($path, 'api/')
        ) {
            $msg = $e->getMessage();
            if (str_contains($msg, 'could not find driver')) {
                return json(
                    [
                        'code' => 500,
                        'msg'  => 'PHP 未启用 MySQL 驱动(pdo_mysql)。请在 php.ini 中启用 extension=pdo_mysql 与 extension=mysqli,保存后重启 PHP / Web 服务。',
                        'data' => [],
                    ],
                    500
                );
            }
            // 上传体积超过 php.ini 时,Request 在进控制器前抛错,需返回 JSON 便于小程序展示
            $isUploadPath = str_contains($path, '/upload') || str_ends_with($path, 'upload');
            if (
                $isUploadPath
                && (
                    str_contains($msg, '上传文件大小超过了最大值')
                    || str_contains($msg, 'upload_max_filesize')
                    || str_contains($msg, 'post_max_size')
                    || str_contains($msg, 'upload File size exceeds')
                    || str_contains($msg, 'file size exceeds')
                )
            ) {
                return json(
                    [
                        'code' => 400,
                        'msg'  => '单张图片超过服务器允许大小。请选较小图片或开启压缩;也可在 php.ini 中调大 upload_max_filesize、post_max_size(须大于单张体积,且 post_max_size ≥ upload_max_filesize)后重启 PHP。',
                        'data' => [],
                    ],
                    400
                );
            }
        }

        return parent::render($request, $e);
    }
}