框架支持异常处理由开发者自定义类进行接管,需要在app
目录下面的provider.php
文件中绑定异常处理类,例如:
// 绑定自定义异常处理handle类
'think\exception\Handle' => '\app\lib\exception\ExceptionHandler',
创建异常类文件,如:app/lib/exception/ExceptionHandler.php
自定义类需要继承think\exception\Handle
并且实现render
方法,可以参考如下代码:
<?php
namespace app\lib\exception;
use think\exception\Handle;
use think\Response;
use Throwable;
class ExceptionHandler extends Handle
{
//定义状态码
public $code;
//定义错误信息
public $message;
//定义错误码
public $errorCode;
public function render($request, Throwable $e):Response
{
//判断$e是不是属于BaseException类传来的值
if($e instanceof BaseException){
$this->code = $e->code;
$this->message = $e->message;
$this->errorCode = $e->errorCode;
}else{
//判断如果是调试模式的输出内容
if(Env::get('APP_DEBUG')){
return parent::render($request, $e);
}
//如果不是则返回特定的信息
$this->code = 500;
$this->message = '服务器异常';
$this->errorCode = '10000';
}
$res = [
'code'=> $this->code,
'message'=>$this->message,
'errorCode'=>$this->errorCode
];
return json($res,$this->code);
}
}
创建调用类文件,如:app/lib/exception/BaseException.php
<?php
namespace app\lib\exception;
use Exception;
class BaseException extends Exception
{
//定义状态码
public $code = 400;
//定义错误信息
public $message = '异常信息';
//定义错误码
public $errorCode = '999';
public function __construct($params = []){
// halt($params);
//判断传过来的值是否是数组,如果不是则返回
if(!is_array($params)) return;
//如果$params传来的有值就修改$this->code的值为传来的值
if(array_key_exists('code',$params)) $this->code=$params['code'];
//如果$params传来的有值就修改$this->message的值为传来的值
if(array_key_exists('message',$params)) $this->message=$params['message'];
//如果$params传来的有值就修改$this->errorCode的值为传来的值
if(array_key_exists('errorCode',$params)) $this->errorCode=$params['errorCode'];
// halt(array_key_exists('code',$params));
}
}
以上就已经封装好了异常处理类,调用方法如下:
//首先在命名空间下面引入类
use app\lib\exception\BaseException;
//在方法里面我们可以这样调用
throw new BaseException(['code'=>560,'message'=>'异常报错','errorCode'=>10000]);