I use LexikJWTAuthentication on a symfony project. The authenticattion work perfectly but I want to customize the exception when no email or password are given in my request.
I found this in the Lexik documentation to customize the exception when authentication fail but is there a way to customize the exception when empty fields are provided ?
I don't think that you can achieve that with Lexik, if no email/password are provided, you got a BAD Request and Lexik can do nothing for you. But Symfony can help you as described in Events and Event Listeners and Built-in Symfony Events
this is a example that work for me in both SF 5 and 6 :
<?php
declare(strict_types=1);
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestListener implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array {
return [
KernelEvents::EXCEPTION => [
['onKernelException']
],
];
}
public function onKernelException(RequestEvent $event) {
dd($throwable = $event->getThrowable());
}
}
$throwable now contain any Exception that can happen in you app, you can check instance of or status codeand implement your own logic there.
in some project, I redirect user to home page instead of 404 error page like that :
if($throwable instanceof NotFoundHttpException) {
$response = new RedirectResponse($this->router->generate('home_page'));
$event->setResponse($response)
}
So that in your case you can do
if ($throwable instanceof BadRequestHttpException) {
$event->setResponse(new Response("Mail is required"));
}
But I don't think is a good solution to do that, because in you case is not the fault of your customer to not having body on request but of the developper , the real case you must check is
{
"email" : "",
"password" : ""
}
And here we got HTTP 401 invalid credential and here your customer must give email/password combination.