avatar

mdo

Hello

  • 首页
  • 知识库
  • 归档
  • 标签
  • 关于
主页 ThinkPHP5之自定义全局异常
文章

ThinkPHP5之自定义全局异常

发表于 2025-12-3 更新于 2025-12- 3
作者 mdo
8~10 分钟 阅读

为了针对书写 api 时,对各种错误返回不通的 json ,直接使用 TP5 自带的提示错误页面,对于客户端而言,明显没有任何的作用,所以需要自己来自定义全局异常。

1.创建一个全局异常的类(用于传错误信息,状态码等)
use think\Exception;
class BaseException extends Exception {

     * @var string
     */
    public $code;


     * @var string
     */
    public $errorCode;


     * @var string
     */
    public $msg;

    public function __construct($params=[])
    {
        if (! $params) {
            return ;
        }


        if ($array_key_exists('code', $code) {
            $this->code = $code;
        }


        if (array_key_exists('errorCode', $params)) {
            $this->errorCode = $params['errorCode'];
        }


        if (array_key_exists('msg', $params)) {
            $this->msg = $params['msg'];
        }
    }
}

这样就可以给以传不通的状态码,错误信息和自定义错误码。

2. 创建一个错误处理类

错误处理类,继承于TP5自带的错误处理类,重写该 render 方法,就可以自定义错误。

use Exception;
use think\exception\Handle;
use think\Request;

class ExceptionHandle extends Handle 
{

     * @var
     */
    private $code;


     * @var
     */
    private $errorCode;


     * @var
     */
    private $msg;


     * @param Exception $e
     * @return \think\response\Json
     */

    public function render(Exception $e) 
    {
        if ($e instanceof BaseException) {




            $this->msg = $e->msg;
            $this->code = $e->code;
            $this->errorCode = $e->errorCode;
        } else {

            if (config('app_debug')) {


                return parent::render($e);
            }
            $this->code = 500;
            $this->msg = '服务器内部错误,不想告诉你';
            $this->errorCode = 999;
            $this->recordErrorLog($e);
        }

        $request = Request::instance();

        $result = [
            'msg' => $this->msg,
            'errorCode' => $this->errorCode,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }


     *  这里把config里日志配置的type改为test
     * @param Exception $e
     */
    private function recordErrorLog(Exception $e)
    {

        Log::init([
            'type'  =>  'File',
            'path'  =>  LOG_PATH,
            'level' => ['error']
        ]);


        Log::record($e->getMessage(),'error');
    }

}
3.修改配置config
    'exception_handle'       => 'app\lib\exception\ExceptionHandle',


'log'                    => [


        'type'  => 'test',

        'path'  => __DIR__.'/../log/',

        'level' => ['sql'],
    ],
4.使用错误类的方法
class UserController extends Controller {

    use app\api\model\User;


    * 根据 id 获取某个用户
    */
    public function getUser($id)
    {
        $user = User::get($id);


        if(! $user) {
            throw UserMissException();
        }

        return json($user);
    }
}

自定义的错误子类

class UserMissException extends BaseException
{

     * @var string
     */
    public $code = '404';


     * @var string
     */
    public $errorCode = '40000';


     * @var string
     */
    public $msg = '请求的用户不存在';
}

请求这个 getUser 方法,报错~ 就会显示

{
    "msg": "请求的用户不存在",
    "errorCode": "40000",
    "request_url": "/api/v1/user/10"
}

其他的错误类型,也就可以继续创建异常子类,定义这些错误属性。

知识库
异常 ThinkPHP5 全局
许可协议:  CC BY 4.0
分享

相关文章

7月 21, 2026

think-orm 2.0.62 单独设置数据表字段缓存驱动和数据缓存驱动

think-cache 拥有强大的多通道(Multi-store)管理能力,但问题的根源在于 think-orm 底层的调用机制太死板。即使您在 think-cache 中配置了 file 和 redis 两个完全独立的通道,think-orm 默认也只会向您通过 Db::setCache() 注入

7月 1, 2026

WebSocket Server + 独立 RPC Server

从架构角度来说,它已经接近 think-swoole 能做到的极限了,但是我仍然不建议继续这样维护。 原因不是代码写法,而是 think-swoole 本身的事件模型。 第一处问题:addListener() 仍然共享 Worker 你的代码: $rpcServer = $server->addLi

6月 25, 2026

Linux | Reqable · API抓包调试 + API测试一站式工具

Reqable是什么? Reqable = Fiddler + Charles + Postman 极简的设计、极高的性能、丰富的功能、桌面手机多端平台。 多协议流量分析 基于经典的MITM中间人代理方案捕获和分析您的应用流量,自适应HTTP/HTTPS/SOCKS4/SOCKS5等多种代理协议,并

下一篇

thinkphp 统一结果返回处理类

上一篇

10款适用于Mac的最佳录音软件

最近更新

  • 完美地解决 TP3 老系统数据的平滑读取
  • thinkphp3 redis序列化和反序列化
  • Table 空间极易发生哈希冲突并溢出
  • 将监控程序直接跑在云端
  • AI 驱动型 Facebook 群组关键词监控 Chrome 浏览器插件

热门标签

API CodeGeex Gitkraken Management Manticore Premiere Sublime Swoole ThinkPHP ThinkPHP5

目录

©2026 mdo. 保留部分权利。