ThinkPHP5之自定义全局异常

作者:mdo 发布时间: 2025-12-03 阅读量:25

为了针对书写 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"
}

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