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);
            }
        }
    }
    

    查看结果

  • 相关阅读:
    C#深入浅出 修饰符(二)
    HDU 5785 Interesting
    HDU 5783 Divide the Sequence
    HDU 5781 ATM Mechine
    UVA 714 Copying Books
    uva 1471 Defense Lines
    UVA 11134 Fabled Rooks
    UVA 11572 Unique Snowflakes
    UVA 11093 Just Finish it up
    UVA 10954 Add All
  • 原文地址:https://www.cnblogs.com/Qyhg/p/14649453.html
Copyright © 2011-2022 走看看