我注意到如果您在使用Laravel例外的策略中使用throw AuthorizationException($message)
,它会跳出策略,但会继续在控制器中执行,并且不会继续执行到Handler::render
。我认为这是他们以某种方式处理异常,但我无法找到他们在做什么......所以如果有人发现这种情况,我仍然想知道。
如果你创建自己的AuthorizationException
扔它,它就会如预期停止执行,并放到Handler::render
所以我最终加入这个方法我的政策:
use App\Exceptions\AuthorizationException;
// ... removed for brevity
private function throwExceptionIfNotPermitted(bool $hasPermission = false, bool $allowExceptions = false, $exceptionMessage = null): bool
{
// Only throw when a message is provided, or use the default
// behaviour provided by policies
if (!$hasPermission && $allowExceptions && !is_null($exceptionMessage)) {
throw new \App\Exceptions\AuthorizationException($exceptionMessage);
}
return $hasPermission;
}
新的异常,在政策投掷只在\App\Exceptions
:
namespace App\Exceptions;
use Exception;
/**
* The AuthorizationException class is used by policies where authorization has
* failed, and a message is required to indicate the type of failure.
* ---
* NOTE: For consistency and clarity with the framework the exception was named
* for the similarly named exception provided by Laravel that does not stop
* execution when thrown in a policy due to internal handling of the
* exception.
*/
class AuthorizationException extends Exception
{
private $statusCode = 403;
public function __construct($message = null, \Exception $previous = null, $code = 0)
{
parent::__construct($message, $code, $previous);
}
public function getStatusCode()
{
return $this->statusCode;
}
}
处理异常,并提供在Handler::render()
以JSON响应消息:
public function render($request, Exception $exception)
{
if ($exception instanceof AuthorizationException && $request->expectsJson()) {
return response()->json([
'message' => $exception->getMessage()
], $exception->getStatusCode());
}
return parent::render($request, $exception);
}
我也将其从登录Handler::report
中删除。
因此,如果引发AuthorizationException,您希望生成自定义错误? – atefth
嗨@atefth yah有点像验证失败时,你得到的错误包,但在这种情况下,你会得到一个失败的政策包与消息,将根据失败的政策作为JSON响应而有所不同。 – mtpultz