Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Catch exception in#[MapRequestPayload] during serialization#60289

Unanswered
andrefpoliveira asked this question inQ&A
Discussion options

Hey!

I have the following controller

final class CreateController{    public function __construct(        ...    ) {}    public function create(        #[MapRequestPayload]        CreateRequestDto $dto,    ): Response {        ...    }}

If the user sends"" or some other input that it's not a JSON structure, I'm gettingNotEncodableValueException, however I would like to catch that and send a custom exception. I already tried ExceptionListener, changing theservices.yaml however it seems that I'm not able to catch it...

use Symfony\Component\HttpKernel\Event\ExceptionEvent;use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;use Symfony\Component\EventDispatcher\Attribute\AsEventListener;use Symfony\Component\Serializer\Exception\NotEncodableValueException;use Symfony\Component\Serializer\Exception\NotNormalizableValueException;#[AsEventListener(event: 'kernel.exception')]      // Tried with and without the eventclass ExceptionListener{    public function __invoke(ExceptionEvent $event): void    {        $exception =  $event->getThrowable();        if ($exception instanceof NotEncodableValueException) {            $event->setThrowable(new BadRequestHttpException());        } elseif ($exception instanceof NotNormalizableValueException) {            $event->setThrowable(new BadRequestHttpException());        }    }}

Is there a way to do this?
Thank you!

You must be logged in to vote

Replies: 1 comment

Comment options

Hello,

you should fix the title so that it readsMapRequestPayload instead ofMapRequestBody!

AFAIU theRequestPayloadValueResolver already convertsNotEncodableValueException toBadRequestHttpException so it is normal you cannot catch it, however you try it.

I guess you could decorate the correspondingargument_resolver.request_payload service, but why do you want to do that? Isn’t theBadRequestHttpException enough?

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@andrefpoliveira@MatTheCat

[8]ページ先頭

©2009-2025 Movatter.jp