Thinkphp5框架异常处理操作实例分析 |
本文标签:Thinkphp5,异常处理 本文实例讲述了Thinkphp5框架异常处理操作 。分享给大家供大家参考,具体如下: 异常处理有时候服务端会报出我们无法感知的错误,TP5默认会自动渲染错误的形式,生产环境中这样的形式并不是我们想要的 。 未知错误1.exceptionHandle.php下的render方法需要覆盖 创建ApiHandleException.php <?php namespace appcommonlibexception; use thinkexceptionHandle; class ApiHandleException extends Handle { /** * http 状态码 * @var int */ public $httpCode = 500; public function render(Exception $e) { return show(0, $e->getMessage(), [], $this->httpCode); } } 2.修改config.php的exception_handle配置项 已知错误我们在判断一个数据是否合法的时候,若不合法则抛出异常 。 例如: if($data['msg'] != 1){ throw Exception('数据异常'); } 使用内置的异常http状态码始终为500 1.创建ApiException.php <?php namespace appcommonlibexception; use thinkException; class ApiException extends Exception { public $message = ''; public $httpCode = 500; public $code = 0; /** * @param string $message * @param int $httpCode * @param int $code */ public function __construct($message = '', $httpCode = 0, $code = 0) { $this->httpCode = $httpCode; $this->message = $message; $this->code = $code; } } 2.对ApiHandleException.php改写 <?php namespace appcommonlibexception; use thinkexceptionHandle; class ApiHandleException extends Handle { /** * http 状态码 * @var int */ public $httpCode = 500; public function render(Exception $e) { if ($e instanceof ApiException) { $this->httpCode = $e->httpCode; } return show(0, $e->getMessage(), [], $this->httpCode); } } 开发环境在开发环境的时候依旧使用异常渲染的模式 在ApiHandleException.php中添加代码 if(config('app_debug') == true) { return parent::render($e); } 更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》 。 希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助 。 |