zoukankan      html  css  js  c++  java
  • thinkphp5.0 异常处理 返回json对象

    新建Banner模型

    applicationapimodelBanner.php

    class Banner
    {
        public static function getBannerById($id)
        {
          //根据id获取banner信息
          return 'this is banner info';
        }
    }
    

    使用banner模型获取对应id的banner
    applicationapicontrollerv1Banner.php

    use appapimodelBanner as BannerModel;
    class Banner
    {
        public function getBanner($id)
        {
          $validate = new IDMustBePositiveInt();
          $validate->goCheck();
          $banner = BannerModel::getBannerByID($id)
          return $banner;
        }
    }
    

    先看看tp自带的异常处理功能
    applicationapimodelBanner.php

    class Banner
    {
        public static function getBannerById($id)
        {
          try{
              1 / 0;
          }catch (Exception $ex) {
              throw $ex; //使用tp5全局异常
          }
          return 'this is banner info';
        }
    }
    

    开启调试模式以查看服务器返回的错误详细信息
    applicationconfig.php

    return [
      'app_debug' => true
    ];
    

    此时调用接口将返回

    用json对象的形式返回
    applicationapicontrollerv1Banner.php

    <?php
    
    
    namespace appapicontrollerv1;
    
    use appapimodelBanner as BannerModel;
    use appapivalidateIDMustBePositiveInt;
    use thinkException;
    
    class Banner
    {
        public function getBanner($id)
        {
            (new IDMustBePositiveInt())->goCheck();
            try {
                $banner = BannerModel::getBannerByID($id);
            } catch (Exception $ex) {
                $err = [
                    'error_code' => 10001,
                    'msg ' => $ex->getMessage()
                ];
                //转成json
                //指明状态码
                return json($err, 400);
            }
        }
    }
    

    查看结果

  • 相关阅读:
    L1和L2正则
    Python基础(一)
    消息分发
    StringList 自定义快速排序
    Delphi Length函数
    接口的委托实现(通过接口)
    接口委托实现--通过类的对象
    排序
    Socket编程(摘抄)
    Delphi线程同步
  • 原文地址:https://www.cnblogs.com/Qyhg/p/14649453.html
Copyright © 2011-2022 走看看