首先定义一个异常类
class BaseException extends Exception
{
public $code = 400;
public $msg = '参数错误';
}
在定义一个类去继承它
class DataMIssException extends BaseException
{
public $code = 404;
public $msg = '请求的数据不存在';
}
目的是区分异常便于处理
全局处理异常开始 重写tp5.1的异常处理方法
class ExceptionHandler extends Handle
{
public function render(Exception $e)
{
if ($e instanceof BaseException) {
$code = $e->code;
$msg = $e->msg;
} else {
$code = $e->getCode();
$msg = $e->getMessage();
Log::write($e->getMessage(),'error');
}
return json(['code' => $code,'data' => [],'msg' => $msg]);
}
}
如果你发生异常,告诉前端出现的问题,由于你处理了异常,前端不用再处理异常,只用判断数据是否为空就好了,否则前端处理异常如果你封装了axios 用try catch ,或者pormise
配置要修改
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => 'app\lib\exception\ExceptionHandler',
路由规则
// http://aqd.cn:7070/hello/he 表示访问 index模块下面 hello 方法 :name 传递参数 接收 $name
Route::get('hello/:name', 'index/hello');