I am currently integrating some logic in App/Exceptions/Handler.php. I would like to be able to access the HTTP Status Code on the $exception variable:
public function report(Throwable $exception)
{
dd($exception->statusCode);
parent::report($exception);
}
However I get the following error:
ErrorException Undefined property: ErrorException::$statusCode
When I dd($exception)
I get the following:
Symfony\Component\HttpKernel\Exception\NotFoundHttpException {#1214 ▼
-statusCode: 404
-headers: []
#message: ""
#code: 0
#file: "C:\Users\CEX\Documents\GitHub\unified\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php"
#line: 43
trace: {▶}
}
How do I access the statusCode
?
PHP Exception getCode() Method The getCode() method returns an integer which can be used to identify the exception.
1 Answer. Show activity on this post. $response->status(); Get the status code for the response.
In Laravel 5 you can catch exceptions by editing the render method in app/Exceptions/Handler. php . This will be applied to ANY exception in AJAX requests. If your app is sending out an exception of App\Exceptions\MyOwnException , you check for that instance instead.
First of all, if you have an HTTP exception, meaning an exception that only makes sense in the context of an HTTP request/response cycle, then you should be able to throw it where it occurs and not throw something else with the purpose of converting it when it reaches the controller, this is what the abort helpers are ...
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();
}
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