convert exception to rest api response

@param GetResponseForExceptionEvent $event
334106
public function onException(GetResponseForExceptionEvent $event)
    {
        if (!$this->eventRequestMatches($event)) {
            return;
        }
        $event->setResponse($this->responseTransformer->createResponseFromContent($event->getException()));
    }
448094
public function handle(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $requestToken = $this->getToken(
            $request->headers->get($this->options['header_name'], null)
        );

        if (!empty($requestToken)) {
            try {
                $decoded = $this->encode->decode($requestToken);
                $user = null;
                if (isset($decoded->{$this->options['username_claim']})) {
                    $user = $decoded->{$this->options['username_claim']};
                }

                $token = new JWTToken(
                    $user,
                    $requestToken,
                    $this->providerKey
                );

                $authToken = $this->authenticationManager->authenticate($token);
                $this->securityContext->setToken($authToken);

            } catch (HttpEncodingException $e) {
            } catch (\UnexpectedValueException $e) {
            }
        }
    }
398740
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($this->isProfilerRequest($event->getRequest())) {
            return;
        }

        $exception = $event->getException();

        if ($exception instanceof DatabaseExceptionInterface) {
            $html = $this->renderDatabaseException($exception);
        } elseif ($exception instanceof AbstractSystemValidationException) {
            $html = $this->renderSystemValidationException($exception);
        } else {
            $html = $this->renderException($exception);
        }

        $statusCode = $exception instanceof HttpExceptionInterface ?
            $exception->getStatusCode() :
            Response::HTTP_INTERNAL_SERVER_ERROR;
        $response = new Response($html, $statusCode, ['X-Debug-Exception-Handled' => time()]);

        $event->setResponse($response);
    }
731698
public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $routeName = $request->attributes->get('_route');
        if (!$route = $this->app['routes']->get($routeName)) {
            return;
        }

        foreach ((array) $route->getOption('_before_middlewares') as $callback) {
            $ret = call_user_func($this->app['callback_resolver']->resolveCallback($callback), $request, $this->app);
            if ($ret instanceof Response) {
                $event->setResponse($ret);

                return;
            } elseif (null !== $ret) {
                throw new \RuntimeException(sprintf('A before middleware for route "%s" returned an invalid response value. Must return null or an instance of Response.', $routeName));
            }
        }
    }
239972
public function onKernelViewSerialize(GetResponseForControllerResultEvent $event)
    {
        if (!$this->isEventEligible($event)) {
            return;
        }

        $annot = $this->extractAnnotation($event, 'OpenOrchestra\BaseApiBundle\Controller\Annotation\Serialize');

        if (!$annot) {
            return;
        }

        $format = $event->getRequest()->get('_format', 'json');
        $statusCode = 200;
        $controllerResult = $event->getControllerResult();
        if ($controllerResult instanceof ConstraintViolationListInterface) {
            $statusCode = 400;
        }

        $event->setResponse(
            new Response(
                $this->generateResponseContent(
                    $controllerResult,
                    $format
                ),
                $statusCode,
                array('content-type' => $this->generateContentType($format))
            )
        );
    }
161034
public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        foreach ($this->requestMatchers as $requestMatcher) {
            if ($requestMatcher->matches($request)) {
                $request->attributes->set(FOSRestBundle::ZONE_ATTRIBUTE, true);

                return;
            }
        }

        $request->attributes->set(FOSRestBundle::ZONE_ATTRIBUTE, false);
    }
688561
private function getPageNotFoundException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if ($exception instanceof PageNotFoundException) {
            return $exception;
        }
        if ($exception->getPrevious() instanceof PageNotFoundException) {
            return $exception->getPrevious();
        }

        return null;
    }
850397
public function onKernelRequest(GetResponseEvent $event)
    {
        // checks if the backend is secured
        $token = $this->securityContext->getToken();
        if (null !== $token) {

            // Check if the user has already been logged in
            $user = $token->getUser();
            if (null !== $user) {
                $errorMessage = '';
                $userId = $user->getId();

                // Frees the expired locked resources and the resource previously locked
                // by the user
                try {
                    $this->resourcesLocker->unlockExpiredResources();
                    $this->resourcesLocker->unlockUserResource($userId);
                } catch (\PropelException $ex) {
                    $errorMessage = $ex->getMessage();
                }

                if ($errorMessage == '') {
                    $request = $event->getRequest();

                    // LOcks the resource
                    $locked = $request->get('locked');
                    if (null !== $locked) {
                        try {
                            // Process composite locking rules
                            $rules = explode(',', $locked);
                            if (isset($rules[1])) {
                                $locked = $rules[0];
                                $param = $request->get($rules[1]);
                            } else {
                                $param = $request->get($locked);
                            }

                            $key = ('locked' !== $locked) ? $locked . "=" . $param : $request->getUri() . '/locked';
                            $this->resourcesLocker->lockResource($userId, md5($key));
                        } catch (\PropelException $ex) {
                            $errorMessage = 'exception_resource_was_free_but_someone_locked_it';
                        }
                    }
                }

                // The resource is not free, stops the request
                if ($errorMessage != '') {
                    throw new ResourceNotFreeException($errorMessage);
                }
            }
        }
    }
594826
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        do {
            if ($exception instanceof AuthenticationException) {
                return $this->handleAuthenticationException($event, $exception);
            } elseif ($exception instanceof AccessDeniedException) {
                return $this->handleAccessDeniedException($event, $exception);
            } elseif ($exception instanceof LogoutException) {
                return $this->handleLogoutException($exception);
            }
        } while (null !== $exception = $exception->getPrevious());
    }
330744
public function onCoreException(GetResponseForExceptionEvent $event)
	{
	    $exception = $event->getException();
	    $request = $event->getRequest();

    	if ($request->isXmlHttpRequest()) {
    		$msg = "";
    		if($exception instanceof AccessDeniedException ) {
    			$msg = "User Not Authenticated";
    		} elseif($exception instanceof AuthenticationCredentialsNotFoundException) {
    			$msg = "User Not Allowed";
    		} elseif($exception instanceof AuthenticationException) {
    			// Change this
    			$msg = "User Not Authenticated";
    		}

    		if($msg) {
    			$responseData = array('status' => 403, 'reason' => $msg);
    			$response = new JsonResponse();
    			$response->setData($responseData);
    			$response->setStatusCode($responseData['status']);
    			$event->setResponse($response);
    		}
	    }
	}
120816
protected function handleException($exception, MvcEvent $event, EventManagerInterface $events)
    {
        // Prepare error event
        $event->setName(MvcEvent::EVENT_DISPATCH_ERROR);
        $event->setError(static::ERROR_EXCEPTION);
        $event->setParam('exception', $exception);

        // Trigger route event
        $result   = $events->triggerEvent($event);
        $response = $result->last();

        if ($response instanceof ResponseInterface) {
            return $this->completeResponse($events, $event, $response);
        }

        return $this->completeRequest($event);
    }
764345
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof SerializationException) {
            $response = $exception->getResponse()
                ->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);

            $event->setResponse($response);
        }
    }
314793
public function onKernelException(GetResponseForExceptionEvent $event): void
    {
        $exception = $event->getException();

        if (!$exception instanceof AccessDeniedException) {
            return;
        }

        $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
    }
507135
public function onKernelException(GetResponseForExceptionEvent $event) :? Response
    {
        // You get the exception object from the received event
        $exception = $event->getException();
        $request = $event->getRequest();

        // If the event already has a response, do not override it.
        if ($event->hasResponse()) {
            return $event->getResponse();
        }

        $format = $request->getRequestFormat($this->defaultFormat);

        // If the request format is not supported, nothing more can be done
        // without the serializer throwing an exception.
        if (!$this->encoder->supportsEncoding($format)) {
            return null;
        }

        // If the normalizer cannot normalize the result, then there is nothing
        // more than can be done without the serializer throwing an exception.
        if (!$this->normalizer->supportsNormalization($exception, $format)) {
            return null;
        }

        $status = 500;
        $headers = [];
        if ($exception instanceof HttpExceptionInterface) {
            $status = $exception->getStatusCode();
            $headers = $exception->getHeaders();
        }

        $context = [
            'enable_max_depth' => true,
        ];

        $serializeEvent = new SerializeEvent($exception, $format, $context, $request);

        $this->eventDispatcher->dispatch(SerializeEvent::NAME, $serializeEvent);

        $response = new Response(
            $this->serializer->serialize(
                $serializeEvent->getData(),
                $serializeEvent->getFormat(),
                $serializeEvent->getContext()
            ),
            $status,
            $headers
        );

        // Add the default content type headers.
        if ($format !== $request->getRequestFormat() && !$response->headers->has('Content-Type')) {
            if ($mimeType = $request->getMimeType($format)) {
                $response->headers->set('Content-Type', $mimeType);
            }
        }

        $event->setResponse($response);

        return $response;
    }
40691
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) { // don't do anything if it's not the master request

            return;
        }

        // We get the exception object from the received event
        $exception = FlattenException::create($event->getException());

        // We get the request
        $request = $event->getRequest();

        // Process the exception
        return $this->logException($exception, $request);
    }
337612
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        // Should return a error 400 bad request
        if ($exception instanceof ValidationException
         || $exception instanceof SyntaxErrorException) {
            return;
        }

        // Some Exceptions have status code and if 400 it should be handled by them
        if (method_exists($exception, 'getStatusCode')
            && (400 == (int)$exception->getStatusCode())) {
            return;
        }

        $data = $this->decorateKnownCases($exception);

        if (!is_array($data)) {
            $data = [
                'code' => $exception->getCode(),
                'exceptionClass' => get_class($exception),
                'message' => $exception->getMessage()
            ];

            if ($exception->getPrevious() instanceof \Exception) {
                $data['innerMessage'] = $exception->getPrevious()->getMessage();
            }
        }

        if ($this->logger instanceof Logger) {
            $this->logger->critical($exception);
        }

        $response = new JsonResponse($data);
        $event->setResponse($response);
    }
186418
public function onKernelException(GetResponseForExceptionEvent $event): void
    {
        $this->originListener->onKernelException($event);

        if (!$event->hasResponse()) {
            // The origin listener not processed.
            return;
        }

        $this->logException($event->getException());
    }