今天在用laravel做前后端分离时 未登录的请求会返回 Unauthenticated 找了下代码
\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php 文件里有这一段
之后就把他直接拿过来放到 App\Exceptions\Handler.php 下并引入异常处理
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
protected function unauthenticated($request, AuthenticationException $exception)
{
return $this->shouldReturnJson($request, $exception)
? response()->json(['message' => $exception->getMessage()], 401)
: redirect()->guest($exception->redirectTo() ?? route('login'));
}
即可自定义
response()->json(['data'=>['message' => $exception->getMessage()]], 401)