ThinkPHP框架中的异常类不适合做为接口开发的异常显示,一般都须要自定义一个符合项目的异常类。restful api数据结构格式通常是:php
在项目中新建文件:application\common\lib\exception\ApiHandleException.php
,继承Handle
类,覆盖掉原来的render
方法异常处理类。实例代码:json
<?php namespace app\common\lib\exception; use think\exception\Handle; class ApiHandleException extends Handle{ public $httpCode = 500; public function render(\Exception $e){ if(config('app_debug') == true){ return parent::render($e); } if($e instanceof ApiException){ $this->httpCode = $e->httpCode; } $data=[ 'status' => 0, 'message' => $e->getMessage() , 'data' => [], ]; return json($data, $this->httpCode); } }
在config.php中加入本身定义的异常类的namespace
路径api
// 异常处理handle类 'exception_handle' => '\app\common\lib\exception\ApiHandleException',
在项目中新建文件:application\common\lib\exception\ApiException.php
,restful
<?php namespace app\common\lib\exception; use think\Exception; class ApiException extends Exception{ public $message = ''; public $httpCode = 500; public $code = 0; public function __construct($message = '', $httpCode = 0, $code = 0){ $this->message = $message; $this->httpCode = $httpCode; $this->code = $code; } }
输出异常例子数据结构
public function test($status){ if($status != 1){ throw new ApiException('提交不合法', 400); } return $status; }