thinkphp6使用自定义异常类


创建自定义异常类基类 app/lib/exception/BaseException.php

<?php


namespace app\lib\exception;

use Exception;
use Throwable;

class BaseException extends Exception
{
    public $code = 400;
    public $msg = '发生错误';
    public $statusCode = 500;

    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->msg = $params['msg'];
        if (array_key_exists('statusCode', $params)) $this->statusCode = $params['statusCode'];

    }
}

创建自定义异常类 app/lib/exception/ExceptionHandler.php

<?php


namespace app\lib\exception;

use Throwable;
use think\exception\Handle;
use think\Response;

class ExceptionHandler extends Handle
{
    public $code;
    public $msg;
    public $statusCode;//http状态码

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->statusCode = $e->statusCode;
        } else {
            // debug开启 显示默认的异常
            if (env('APP_DEBUG')) return parent::render($request, $e);
            $this->code = 500;
            $this->msg = '服务器异常';
            $this->statusCode = 500;
        }
        $res = [
            'msg' => $this->msg,
            'code' => $this->code,
        ];
        return json($res, $this->statusCode);
    }
}

修改thinkphp6异常类使用自定义的异常类 app/provider.php

<?php
use app\lib\exception\ExceptionHandler;
use app\Request;
use app\ExceptionHandle;

// 容器Provider定义文件
return [
    'think\Request'          => Request::class,
    'think\exception\Handle' => ExceptionHandler::class,
//    'think\exception\Handle' => ExceptionHandle::class,
];

在控制器中使用抛出自定义异常类 app/index/controller/Index.php

<?php


namespace app\index\controller;

use app\BaseController;
use think\facade\Request;
use app\lib\exception\BaseException;

class Index extends BaseController
{
    public function index()
    {
        throw (new BaseException(['code'=>400,'statusCode'=>404,'msg'=>'异常']));
        return '111';
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM