class Banner { public static function getBannerById($id) { try{ 1 / 0; }catch (Exception $ex) { throw $ex; //使用tp5全局异常 } return 'this is banner info'; } }
开启调试模式以查看服务器返回的错误详细信息
application\config.php
return [ 'app_debug' => true ];
此时调用接口将返回
这个异常页面可以清楚看到代码中的哪个地方出错,方便调试代码,但在生产环境下我们则希望返回一个json对象并且记录日志
application\lib\exception\BaseException.php
<?php namespace app\lib\exception; use think\Exception; class BaseException extends Exception { //统一描述错误,可重写 public $code = 400; public $msg = 'invalid parameters'; public $errorCode = 999; /** * 构造函数,接收一个关联数组 * @param array $params 关联数组只应包含code、msg和errorCode,且不应该是空值 */ public function __construct($params=[]) { if(!is_array($params)){ return; } if(array_key_exists('code',$params)){ $this->code = $params['code']; } if(array_key_exists('msg',$params)){ $this->msg = $params['msg']; } if(array_key_exists('errorCode',$params)){ $this->errorCode = $params['errorCode']; } } }
对tp5异常处理类进行重写
application\config.php
return [ 'exception_handle'=>'\app\lib\exception\ExceptionHandler', ];
application\lib\exception\ExceptionHandler.php
<?php namespace app\lib\exception; use think\exception\Handle; use think\Log; use think\Request; use Exception; class ExceptionHandler extends Handle { private $code; private $msg; private $errorCode; public function render(Exception $e) { //如果这个错误是自己编写的代码抛出的 if ($e instanceof BaseException) { $this->code = $e->code; $this->msg = $e->msg; $this->errorCode = $e->errorCode; } else{ // 加个开关,让前后台都能接收到方便阅读的信息 // config是tp5助手函数,用于读取配置信息 if(config('app_debug')){ // 调试状态下需要显示TP默认的异常页面,是供后端人员浏览的信息 // 不会记录日志 return parent::render($e); } $this->code = 500; $this->msg = 'sorry,we make a mistake. (^o^)Y'; $this->errorCode = 999; $this->recordErrorLog($e); } $request = Request::instance(); $result = [ 'msg' => $this->msg, 'error_code' => $this->errorCode, 'request_url' => $request = $request->url() ]; return json($result, $this->code); } /* * 将异常写入日志 */ private function recordErrorLog(Exception $e) { Log::init([ 'type' => 'File', 'path' => LOG_PATH, 'level' => ['error'] ]); Log::record($e->getMessage(),'error'); } }
application\lib\exception\ParameterException.php
class ParameterException extends BaseException{ public $code = 400; public $msg = '参数错误'; public $errorCode = 10000; }
application\api\validate\BaseValidate.php
<?php namespace app\api\validate; use app\lib\exception\ParameterException; use think\Request; use think\Validate; class BaseValidate extends Validate { // 检测所有客户端发来的参数是否符合验证类规则 public function goCheck() { $request = Request::instance(); $params = $request->param(); //同时校验多个规则 $result = $this->batch()->check($params); if (!$result) { $e = new ParameterException([ 'msg' => $this->error, 'code' => 400, 'errorCode' => 10002 ]); throw $e; } else { return true; } } }