我注意到如果您在使用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