本文实例讲述了thinkphp5框架异常处理操作。分享给大家供大家参考,具体如下:
异常处理
有时候服务端会报出我们无法感知的错误,tp5默认会自动渲染错误的形式,生产环境中这样的形式并不是我们想要的。
未知错误
1.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);
}
}
2.修改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);
}
很明显