Why is it not rendered in a given way? Other types of exceptions are working well except AccessDeniedHttpException
App/Exceptions/Handler.php
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException as AccessDeniedHttpException;
...
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
...
// 403 Forbidden
if ($exception instanceof AccessDeniedHttpException)
{
return response()->json([
'code' => 403,
'message' => 'This action is unauthorized1.',
],403);
}
// 401 Unauthorized
if ($exception instanceof AuthenticationException)
{
return response()->json([
'code' => 401,
'message' => 'Unauthenticated error.',
], 401);
}
The 401 is working like a charm, but the 403 do the original rendering.
Any solutions?
Try and include this in your App\Exceptions\Handler.php
. Be sure to add use Illuminate\Auth\Access\AuthorizationException;
at the top of your Hander.php
:
protected $dontReport = [
\Illuminate\Auth\Access\AuthorizationException::class,
];
Apparently, AccessDeniedHttpException
is an instance of AuthorizationException
.
public function render($request, Exception $exception)
{
//Useful since some methods cannot be accessed in certain URL extensions
if ($exception instanceof AuthorizationException) {
return response()->view('errors.404', [], 404);
}
return parent::render($request, $exception);
}
class CouponStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;//please change the authorize return to true in request file.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With