首页 > Windows开发 > 详细

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

时间:2020-02-21 12:30:22      阅读:456      评论:0      收藏:0      [点我收藏+]

技术分享图片

重写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;
    }
}

 

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

原文:https://www.cnblogs.com/zhangcheng001/p/12340664.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!