How do I get the HTTP Status Code from an Exception thrown in Laravel?
If you look at the source code of Symfony\Component\HttpKernel\Exception\NotFoundHttpException
you will find that it extends Symfony\Component\HttpKernel\Exception\HttpException
if you look at the declaration of the class you will see that $statusCode
is private but it has a getter method
class HttpException extends \RuntimeException implements HttpExceptionInterface
{
private $statusCode;
private $headers;
public function __construct(int $statusCode, string $message = null, \Throwable $previous = null, array $headers = [], ?int $code = 0)
{
$this->statusCode = $statusCode;
$this->headers = $headers;
parent::__construct($message, $code, $previous);
}
public function getStatusCode()
{
return $this->statusCode;
}
//...
}
As such you simply need to do $exception->getStatusCode()
to retrieve the status code (404 in your case) though you should do a check to make sure your throwable implements the HttpExceptionInterface
because that might not always be the case and so the method would not exist and you would get a fatal error
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface) {
$code = $exception->getStatusCode();
}