private function createJsonResponseIfNeeded(
        GetResponseEvent $event,
        $result
    ) {
        /**
         * Only flushes if exists AnnotationFlush as a controller annotations.
         */
        if ($this->returnJson) {
            if ($result instanceof Exception) {
                $this->status = $result instanceof HttpExceptionInterface
                    ? $result->getStatusCode()
                    : $this->defaultErrorStatus;

                $result = [
                    'code' => $result->getCode(),
                    'namespace' => get_class($result),
                    'message' => $result->getMessage(),
                ];
            }

            $response = JsonResponse::create(
                $result,
                $this->status,
                $this->headers
            );

            $event->setResponse($response);
        }
    }