Reputation: 28661
I have a service that is helping me to validate some forms. I want to set HTTP status code from inside of it when it finds that form is actually invalid.
Is it OK to do so? How do I do it? Thanks!
Upvotes: 0
Views: 1148
Reputation: 10910
The way I would do that (probably there's lot more solutions) is throwing some (custom) exception in your service in case your form is invalid.
Then I would create an exception listener which would listen on kernel exception event. Configuration of such listener would look something like this (services.yml
)
kernel.listener.your_listener:
class: Acme\Your\Namespace\YourExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onException }
And than your onException
method in YourExceptionListener
class:
public function onException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof YourCustomExceptionInterface) {
$response = new Response('', 400);
$event->setResponse($response);
}
}
This way you get nicely decoupled stuff, and your form validation service is independent of response.
Upvotes: 2