By default, if an application throws an exception, Symfony will turn that exception into an error with 500 HTTP status code, unless exception implements the HttpExceptionInterface
or extends a class that implements that interface (e.g. HttpException
).
This tutorial shows how to define the HTTP status code of the exception in Symfony 7 application.
Let's say we have a controller that throws InvalidArgumentException
provided by Validator component.
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
class TestController
{
#[Route('/')]
public function index(): Response
{
throw new InvalidArgumentException();
}
}
We will get 500 Internal Server Error if we try to open associate URL of that controller.
Symfony allows defining HTTP status code of the exception by using framework.exceptions
option.
framework:
exceptions:
Symfony\Component\Validator\Exception\InvalidArgumentException:
status_code: 422
Now exception will be turned into an error with status code 422 Unprocessable Content.
Leave a Comment
Cancel reply