本文实例讲述了Thinkphp5框架异常处理操作。分享给大家供大家参考,具体如下:
异常处理
当服务端出现开发者难以察觉的错误时,TP5默认会自动渲染错误页面,但在生产环境中这种展示方式通常不符合需求。
未知错误
需要覆盖exception\Handle.php文件下的render方法以实现自定义处理。
首先创建ApiHandleException.php类。
<?php
namespace app\common\lib\exception;
use think\exception\Handle;
class ApiHandleException extends Handle {
/**
* http 状态码
* @var int
*/
public $httpCode = 500;
public function render(\Exception $e) {
return show(0, $e->getMessage(), [], $this->httpCode);
}
}
其次,修改config.php配置文件中的exception_handle配置项,指向新创建的异常处理器。
已知错误
在进行数据合法性校验时,若发现数据不合法,应主动抛出异常以中断流程或记录日志。
例如:
if($data['msg'] != 1){
throw Exception('数据异常');
}
使用内置的异常http状态码始终为500
1.创建ApiException.php
<?php
namespace app\common\lib\exception;
use think\Exception;
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 app\common\lib\exception;
use think\exception\Handle;
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框架的PHP程序设计有所帮助。