thinkphp8接管异常处理类
创建文件app\Http.php
<?phpdeclare (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,
];