• 2022-09-04被罚款200元记6分.
  • 特么的.电脑风扇坏了.快递还全部停发.太难了...求求了.疫情赶紧走吧.
  • 难啊难!要钱难!
  • 更新到WordPress5.6啦
  • 有点伤心了,今年净遇到王某海这种人.
  • 难啊难...
  • 七牛的JS SDK 的文档真坑啊.
  • 蓝奏云分享部分地区无法访问需手动修改www.lanzous.com变为:www.lanzoux.com
  • 好气啊~原来使用的CDN服务商莫名其妙的给我服务取消了~
  • 遇见一个沙雕汽车人.

ThinkPHP5自定义抛出异常

PHP KIENG 3年前 (2020-04-22) 61036次浏览 已收录 1个吐槽 扫描二维码

ThinkPHP5 自定义抛出异常

建立 application 下建立common/exception目录.

新建ExceptionHandler.php

<?php

namespace app\common\exception;

use think\exception\Handle;
use think\Log;
use Exception;

/**
 * 重写 Handle 的 render 方法,实现自定义异常消息
 * Class ExceptionHandler
 * @package app\common\library\exception
 */
class ExceptionHandler extends Handle
{
    private $code;
    private $message;

    /**
     * 输出异常信息
     * @param Exception $e
     * @return \think\Response|\think\response\Json
     */
    public function render(Exception $e)
    {
        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->message = $e->message;
        } else {
            if (config('app_debug')) {
                return parent::render($e);
            }
            $this->code = 0;
            $this->message = $e->getMessage() ?: '很抱歉,服务器内部错误';
            $this->recordErrorLog($e);
        }
        return json(['msg' => $this->message, 'code' => $this->code]);
    }

    /**
     * 将异常写入日志
     * @param Exception $e
     */
    private function recordErrorLog(Exception $e)
    {
        Log::record($e->getMessage(), 'error');
        Log::record($e->getTraceAsString(), 'error');
    }
}

新建BaseException.php

<?php

namespace app\common\exception;

use think\Exception;

/**
 * Class BaseException
 * 自定义异常类的基类
 */
class BaseException extends Exception
{
    public $code = 0;
    public $message = 'invalid parameters';

    /**
     * 构造函数,接收一个关联数组
     * @param array $params 关联数组只应包含 code、msg,且不应该是空值
     */
    public function __construct($params = [])
    {
        if (!is_array($params)) {
            return;
        }
        if (array_key_exists('code', $params)) {
            $this->code = $params['code'];
        }
        if (array_key_exists('msg', $params)) {
            $this->message = $params['msg'];
        }
    }
}

在模块目录下或全局config.php里修改:

'default_return_type' => 'json',
// 异常处理 handle 类 留空使用 \think\exception\Handle
'exception_handle' => 'app\common\exception\ExceptionHandler',

这样用 THINKPHP5 写 API 报错就不会返回 html 页面拉..返回是 json 格式.


KIENG.CN , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA 4.0协议进行授权
转载请注明出处:ThinkPHP5 自定义抛出异常
本文章链接:https://blog.kieng.cn/2372.html
喜欢 (19)
KIENG
关于作者:
一个热衷网络的Man
发表我的评论
取消评论
表情 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 快速获取昵称
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(1)个小伙伴在吐槽
  1. 很棒哟
    很棒哟 | 中国江苏苏州市 电信2020-04-30 14:57 回复 Windows 7 | Chrome 81.0.4044.122