Auth 授权的异常捕获
上技师
路由中我们有使用 auth
中间件,所以打开修改 App\Http\Middleware\Authenticate.php
中间件。
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use App\Exceptions\AuthException;
class Authenticate extends Middleware
{
/**
* 重写未授权方法
*
* @param $request
* @param array $guards
* @return void
* @throws AuthException
*/
protected function unauthenticated($request, array $guards): void
{
throw new AuthException();
}
}
AuthException
是我自定义的异常类,最终返回的是 response
响应。
原理
App\Http\Middleware\Authenticate
继承 Illuminate\Auth\Middleware\Authenticate
,父类中有个 unauthenticated
方法,抛出的异常是 Illuminate\Auth\AuthenticationException
,我们只需要重写这个方法就好了。
原中间件 App\Http\Middleware\Authenticate
中只有 redirectTo
这个方法。重写 unauthenticated
方法后,redirectTo
就可以删除了。
其他方法
App\Exceptions\Handler.php
中,向 render
方法中添加如下代码:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Middleware\Authenticate;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Exceptions\AuthException;
class Handler extends ExceptionHandler
{
...
public function render($request, Exception $exception)
{
if ($exception instanceof AuthenticationException) {
throw new AuthException();
}
return parent::render($request, $exception);
}
}
在论坛上看了也不知道是谁的文章,说 render
方法中不能过多的使用 instanceof
所以打开源码简单看了一下。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: