TP5使用API时不可预知的内部异常

  • 2019 年 10 月 3 日
  • 笔记

最常见的错误形式例如 controller不存在或者 action不存在之类的 我们第一时间想到的 就是 使用 try{}catch(){} 来捕获 例如:

    /**       * show方法在common里定义过--统一返回接口       * @return array       */      public function Test(){          try{              model("asda");          }catch (Exception $e){              return show(0,$e->getMessage(),'',400)          }      }      

但是有的错误我们是没有办法捕获到的 会返回如下格式

我们API是没有办法识别的 所以遇到这种情况 我们应该怎么解决呢?

首先 不论什么框架 他都有自己的 错误渲染机制 我们应当找到这个渲染机制 去修改它 TP5框架 在 thinkphp/library/think/exception/Handle.php 中 在这个文件中 有一个 render 方法

  /**       * Render an exception into an HTTP response.       *       * @param  Exception $e       * @return Response       */      public function render(Exception $e)      {          if ($this->render && $this->render instanceof Closure) {              $result = call_user_func_array($this->render, [$e]);              if ($result) {                  return $result;              }          }            if ($e instanceof HttpException) {              return $this->renderHttpException($e);          } else {              return $this->convertExceptionToResponse($e);          }      }

我们需要重写这个方法 使之返回我们想要json格式数据

新建一个类来继承Handle类

<?php  namespace appcommonlibexception;  use thinkexceptionHandle;    /**   * Created by PhpStorm.   * User: Administrator   * Date: 2019/8/15   * Time: 11:20   */  class ApiHandleException extends Handle  {      public $httpCode = 500;          public function render(Exception $e){          return show(0,$e->getMessage(),[], $this->httpCode);      }  }

写好之后 我们还需要在TP5的配置文件中 修改异常处理类 在applicationconfig.php中 大概163行

'exception_handle'       => 'appcommonlibexceptionApiHandleException',

指向我们重构的类

接下来我们再去请求 就会返回我们想要的json格式啦

但是问题随之而来了 如果我们出现如下代码报错的话 状态会是 500

    public function test(){          $data = [              'aa' => 1,              'ss' => 2,          ];          if($data['ss'] != 1){              exception('你提交的数据有问题');          }      }

所以需要我们去创建一个 内部的异常类  

<?php  /**   * Created by PhpStorm.   * User: Administrator   * Date: 2019/8/15   * Time: 11:36   */    namespace appcommonlibexception;      use thinkException;    class ApiException extends  Exception  {      public $message = '';      public $httpCode = 500;      public $code = 0;          public function  __construct($message = '' , $httpCode = 0, $code = 0)      {          $this->httpCode = $httpCode;          $this->message = $message;          $this->code = $code;      }  }

创建好了之后 我们需要去修改我们之前创建的  ApiHandleExecption  类

<?php  namespace appcommonlibexception;  use thinkexceptionHandle;    /**   * Created by PhpStorm.   * User: Administrator   * Date: 2019/8/15   * Time: 11:20   */  class ApiHandleException extends Handle  {      public $httpCode = 500;        public function render(Exception $e){          if ($e instanceof ApiException) {
       ##$e->httpCode 就是ApiException里面的 $this->httpCode;
$this->httpCode = $e->httpCode; } return show(0,$e->getMessage(),[], $this->httpCode); } }

这样我们的状态码也会随之改变  不过 我们还需要在进一步的 优化 ApiHandleException 类 因为 这样的异常形式 是给API看的 而我们在开发的时候 是需要渲染错误的 所以我们修改一下代码

<?php  namespace appcommonlibexecption;  use thinkConfig;  use thinkexceptionHandle;    /**   * Created by PhpStorm.   * User: Administrator   * Date: 2019/8/15   * Time: 11:20   */  class ApiHandleExecption extends Handle  {      public $httpCode = 500;        public function render(Exception $e){
     ##判断debug模式是否开启 如果开启 用他父级的 render方法 进行异常渲染
if(config('app_debug') == true){ return parent::render($e); } if ($e instanceof ApiException) { $this->httpCode = $e->httpCode; } return show(0,$e->getMessage(),[], $this->httpCode); } }

 至此我们的 内部异常就解决了 梳理下流程 :

首先我们需要 找到 内部异常渲染类(ApiHandleException) 重构它的render方法 重构之后 我们需要进一步的 更改状态码 所以需要新建 一个 类(ApiException)来初始化他们的状态码等数据 初始化之后 我们还需要进一步修改我们自己写的异常渲染类(ApiHandleException) 使之在debug模式下 可以正常渲染