步骤:
定义返回浏览器异常错误格式
1、处理输入错误url提示
2、token验证失败提示信息
参考文档:
https://learnku.com/docs/laravel/7.x/errors/7468
实现代码
所有异常都是由 App\Exceptions\Handler.php 处理
#使用NotFoundHttpException处理路由错误
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function render($request, Throwable $exception)
{
//判断当前请求是否为json请求
if ($request->expectsJson()) {
//判断当前异常是否为NotFoundHttpException的实例,指定找不到路径返回错误信息
if ($exception instanceof NotFoundHttpException) {
return response()->json([
'ret' => 404,
'msg' => 'no found path:' . $request->path(),
'data' => []
], 200);
}
}
return parent::render($request, $exception);
}
//token验证不通过错误信息返回提示格式设置
protected function unauthenticated($request, \Illuminate\Auth\AuthenticationException $exception)
{
//判断当前是否为json,是则返回地洞错误信息,不是则重定,找不到则到login下
return $request->expectsJson() ? response()->json([
'ret' => 401,
'msg' => '请登录',
'data' => []
]):redirect()->guest($exception->redirectTo()?? route('login'));
}
token权限验证错误提示信息