接管ThinkPHP5框架的异常处理
- ThinkPHP
- 时间:2021-04-11
- 666人已阅读
简介接管ThinkPHP5框架的异常处理
首先配置tp5框架的配置文件,使用自己写的异常处理handle类
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => 'app\lib\exception\ExceptionHandler',
1.自定义类需要继承think\exception\Handle
并且实现render
方法
<?php
namespace app\lib\exception;
use Exception;
use think\exception\Handle;
use think\facade\Request;
class ExceptionHandler extends Handle
{
protected $code;
protected $msg;
protected $errCode;
public function render(Exception $e)
{
if ($e instanceof BaseException) { //如果异常属于自定义的异常类
$this->code = $e->code;//http状态码
$this->msg = $e->msg;//错误消息
$this->errCode = $e->errCode;//错误码
} else {
$switch = config('app_debug');//获取应用的调试模式状态
if ($switch) { //如果调试模式开启,返回tp5默认的错误页面
return parent::render($e);
} else {
$this->code = 500;//http状态码
$this->msg = '服务器内部错误,不想告诉你';//错误消息
$this->errCode = 999;//错误码
}
}
$result = [
'msg' => $this->msg,//错误消息
'errCode' => $this->errCode,//错误码
'request_url' => Request::url(),//请求url
];
return json($result, $this->code);
}
}
2.自定义异常基类
<?php
namespace app\lib\exception;
use think\Exception;
class BaseException extends Exception
{
public $code = 400;
public $msg = "参数错误";
public $errCode = 10000;
}
3.自定义异常类继承异常基类
<?php
namespace app\lib\exception;
class ParamsException extends BaseException
{
public $code = 400;
public $msg = "参数错误";
public $errCode = 10000;
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('errCode', $params)) {
$this->errCode = $params['errCode'];
}
}
}
4.测试代码
<?php
namespace app\api\controller\v1;
use app\lib\exception\ParamsException;
class Banner
{
//测试代码
public function getBanner()
{
throw new ParamsException([
'msg' => "name不能为空!"
]);
}
}
5.运行效果
---------------------------------------------------------------------------------------------------------