自定义异常处理类 1>class ExceptionHandler extends Handle 继承 Handle 2>public function render(Exception $e) 重写render方法 3>config.php中 配置exception_handle 指向自定义的异常处理类 // 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle' => 'app\lib\exception\ExceptionHandler', 4>render()中 判断 两种异常
<?php
namespace app\lib\exception;
use think\Exception;
use think\exception\Handle;
use think\Log;
use think\Request;
class ExceptionHandler extends Handle
{
/**
* @code HTTP状态码
* @msg 错误信息
* @errorCode 自定义错误码
* $request->url() 客户端请求的当前URL
*/
private $code ;
private $msg ;
private $errorCode ;
/**
* @param Exception $e
* @return string|\think\Response
* 重写 render方法 框架会传过来需要处理的异常
* 所有抛出的Exception 都会通过render()方法渲染
*/
public function render(Exception $e)
{
/**
* 判断两种异常
* 1>客户端参数异常 不记录日志 返回错误信息
* BaseException
* 2>服务器端异常 记录日志 不返回信息
*/
if($e instanceof BaseException){
//属于 自定义异常
$this->code = $e->code ;
$this->msg = $e->msg ;
$this->errorCode = $e->errorCode ;
}
else{
//开发环境 使用默认的报错页面便于调试 生产环境 返回json格式报错信息
if(config('app_debug')) {
//开发环境 调用父类 默认的报错页面
return parent::render($e) ;
}else{
//服务器错误
$this->code = 500 ;
$this->msg = '服务器内部错误' ;
$this->errorCode = 999 ;
//记录日志
$this->recordErrorLog($e) ;
}
}
//request对象 实例化
$request = Request::instance() ;
$results = [
'msg' => $this->msg ,
'error_code' => $this->errorCode ,
'request_url' => $request->url()
] ;
return json($results,$this->code);
}
/**
* @param Exception $e
* 记录日志 重写recordErrorLog()
* Log::record(日志信息,错误级别)
*/
private function recordErrorLog(Exception $e)
{
//关闭了自动记录日志 此处需要手动初始化
Log::init([
// 日志记录方式,内置 file socket 支持扩展
'type' => 'File',
// 日志保存目录
'path' => LOG_PATH,
// 日志记录级别
'level' => ['error'],
]);
//$e->getMessage() 获取日志信息 'error'记录日志错误级别
Log::record($e->getMessage(),'error');
}
}
<?php
namespace app\lib\exception;
use think\Exception;
use Throwable;
class BaseException extends Exception
{
//HTTP状态码 200 404
public $code = 400;
//错误具体信息
public $msg = '参数错误' ;
//自定义错误码
public $errorCode = 10000 ;
/**
* BaseException constructor.
* @param array $params
* 定义构造函数 可以对上面三个参数 赋值 获取时时报错信息
* 可选参数赋值 code errorCode 默认 msg信息覆盖
* 不使用 构造方法参数赋值 抛异常的时候 $e->msg = $this->error ;
*/
public function __construct($params = [])
{
//判断传入参数是否是数组
if(!is_array($params)) {
//直接 return 或者 抛出异常都可
return ;
//throw new Exception('参数必须是数组') ;
}
//判断 $params 中是否有code
if(array_key_exists('code',$params)) {
$this->code = $params['code'] ;
}
//判断 $params中是否有 msg
if(array_key_exists('msg',$params)) {
$this->msg = $params['msg'] ;
}
//判断 $params中是否有 errorCode
if(array_key_exists('errorCode',$params)) {
$this->errorCode = $params['errorCode'] ;
}
}
}