tp5.1 API接口 自定义抛出异常

重写Handel的render()方法

<?php

namespace app\lib\exception;

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

class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    // 需要返回客户端当前请求的URL路径 

    public function render(\Exception $e)
    {
        if ($e instanceof BaseException) {
            // 如果是自定义的异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
            Log::close(); //关闭日志写入
        } else {
            if (config('app.app_debug')) {
                return parent::render($e);
            } else {
                $this->code = 500;
                $this->msg = '服务器内部错误';
                $this->errorCode = 999;
            }
        }
        $result = [
            'msg' => $this->msg,
            'error_code' => $this->errorCode,
            'request_url' => request()->url()
        ];
        return json($result, $this->code);
    }
}

在配置文件中,修改异常处理类地址

默认输出类型改为 json

基础异常类

<?php

namespace app\lib\exception;

use think\Exception;

class BaseException extends Exception
{
    // http状态码 正常200
    public $code = 400;
    // 错误具体信息
    public $msg = '参数错误';
    // 自定义的错误码
    public $errorCode = 10000;

    public function __construct($params = [])
    {
        if (!is_array($params)) {
            // return;
            throw new Exception('参数必须是数组');
        }
        if(array_key_exists('code',$params)){
            $this->code = $params['code'];
        }
        if(array_key_exists('msg',$params)){
            $this->msg = $params['msg'];
        }
        if(array_key_exists('errorCode',$params)){
            $this->errorCode = $params['errorCode'];
        }
    }
}

自定义异常  例如自定义一个轮播图异常

<?php

namespace app\lib\exception;

class BannerMissException extends BaseException
{
    public $code = 404;
    public $msg = '请求的banner不存在';
    public $errorCode = 40000;
     
}

如果查询的轮播图信息不存在,抛出该异常

<?php

namespace app\api\controller\v1;

use app\api\validate\IDMustBePositiveInt;
use app\lib\exception\BannerMissException;
use think\Controller;

class Banner extends Controller
{
    /**
     * 获取指定id的banner轮播图信息
     * @url /banner/:id
     * @http GET
     * @id banner的id号
     */
    public function getBanner($id)
    {
        // 验证参数id
        (new IDMustBePositiveInt())->goCheck();
        // 查询banner信息
        $banner = model('Banner')->getBannerID($id);
        if (!$banner) {
            // 如果查询不存在 抛出自定义异常信息
            throw new BannerMissException();
        }
        return $banner;
    }
}

猜你喜欢

转载自www.cnblogs.com/zhangcheng001/p/12340664.html