Symfony 5 – best practices to handle query exception

i want to ask more experienced symfony dev about exception handling.
I know i should make and EventListener and inside handle exceptions.

But what if i got isnert into exception value should not be null?

public function onKernelException(ExceptionEvent $event)
{
    $exception = $event->getThrowable();
    $message = sprintf(
        'ERROR:%s|CODE:%s',
        $exception->getMessage(),
        $exception->getCode()
    );

    $response = new Response();
    $response->setContent($message);

    if ($exception instanceof PDOException) {
        $response->setStatusCode($exception->getStatusCode());
        $response->headers->replace($exception->getHeaders());
    } else {
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    $event->setResponse($response);
}

    AppEventListenerRuneBonusInsertExceptionListener:
    tags:
        - { name: kernel.event_listener, event: kernel.exception }

is that right or should i do this in other way?

The second idea i got is handle this in action controller something like:

    public function addNewBonus(Request $request, RuneBonusRegisterer $registerer)
    {
        $bonusData = json_decode($request->getContent(), true);

        $form = $this->createForm(RuneBonusType::class);
        $form->submit($bonusData);

        if (!$form->isValid()) {
            return $this->json([
                'errors' => $form->getErrors(true, false)
            ], 200);

        }

        $bonus = $form->getData();
        $registerer->register($bonus);

        return $this->json(
            $bonus, 200
        );
    }

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *