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

查看结果

原文地址:https://www.cnblogs.com/Qyhg/p/14649453.html