Render json

@param ServerErrorsException $exception
@return void
174868
private function toJson(ServerErrorsException $exception)
  {
    Rest::response()->json([
      'status' => $exception->getMessage(),
      'code'   => $exception->getStatusCode()
    ], $exception->getStatusCode());
  }
168640
public function renderException(\Exception $exception)
    {
        $verbose = $this->console ? $this->console->get('verbose', 0) : 0;

        if (!$verbose) {
            $this->out()->err($exception->getMessage());

            return;
        }

        /** @var $exception \Exception */
        $class = get_class($exception);

        // @codingStandardsIgnoreStart
        $output = <<<EOF
<error>Exception '{$class}' with message:</error> <fg=cyan;options=bold>{$exception->getMessage()}</fg=cyan;options=bold>
<info>in {$exception->getFile()}:{$exception->getLine()}</info>

<error>Stack trace:</error>
{$exception->getTraceAsString()}
EOF;
        // @codingStandardsIgnoreEnd

        $this->out('');
        $this->err($output);
    }
756827
protected function renderJsonErrorMessage(Exception $exception)
    {
        $error = [
            'message' => 'Slim Application Error',
        ];

        if ($this->displayErrorDetails) {
            $error['exception'] = [];

            do {
                $error['exception'][] = [
                    'type' => get_class($exception),
                    'code' => $exception->getCode(),
                    'message' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'trace' => explode("\n", $exception->getTraceAsString()),
                ];
            } while ($exception = $exception->getPrevious());
        }

        return json_encode($error, JSON_PRETTY_PRINT);
    }
382852
protected function renderApplication(Exception $e)
    {
        $response = $this->getExceptionHandler()->render($this->app['request'], $e);
        $response->send();
    }
687659
private function _handleException(Exception $exception)
    {
        $status = $exception->getCode();
        $statusText = \Slim\Http\Response::getMessageForCode($status);

        if ($statusText === null) {
            $status = 500;
            $statusText = 'Internal Server Error';
        }

        //Get app environment variables
        $env = $this->app->environment;

        $this->app->response->setStatus($status);

        if (isset($env['auth.JSONerrors']) && $env['auth.JSONerrors'] == true) {
            $this->app->response->headers->set('Content-Type', 'application/json');
            $this->app->response->setBody(
                json_encode(
                    [
                        'status' => ($status < 500) ? 'fail' : 'error',
                        'data' => [
                            'status' => $status,
                            'statusText' => preg_replace('/^[0-9]+ (.*)$/', '$1', $statusText),
                            'description' => $exception->getMessage(),
                        ],
                    ]
                )
            );
        } else {
            $this->app->response->setBody('<h1>'.$statusText.'</h1><h4>'.$exception->getMessage().'</h4>');
        }

        $this->app->response()->finalize();

        return $this->app->response();
    }
1275519
public function renderView() {
		header('Content-Type: application/json;charset=utf-8');
		$json = json_encode($this->getViewVariables());
		if ($json) {
			echo $json;
		} else {
			throw new \RuntimeException($this->getEncodeErrors()[json_last_error()]);
		}
	}
1183347
public function render($request, Exception $e)
    {
        if ($this->isServiceException($e)) {
            $e->setRequest($request);
        } elseif ($e instanceof ValidationException) {
            $e = $this->convertValidationExceptionToEntityException($e);
        } else {
            $e = $this->convertExceptionToServiceException($e);
        }

        return $this->prepareJsonResponse($e);
    }
522383
public function render($exception)
    {
        for ($level = ob_get_level(); $level > 0; $level--) {
            ob_end_clean();
        }

        if ($this->configure->debug) {
            if ($this->renderer->exists('@views/Errors/debug')) {
                return $this->renderer->render('@views/Errors/debug', ['exception' => $exception]);
            } else {
                return $this->renderer->render('@manaphp/Mvc/ErrorHandler/Views/debug', ['exception' => $exception]);
            }
        }

        $statusCode = $exception instanceof \ManaPHP\Exception ? $exception->getStatusCode() : 500;

        foreach (["@views/Errors/$statusCode",
                     '@views/Errors/error'] as $template) {
            if ($this->renderer->exists($template)) {
                return $this->renderer->render($template, ['statusCode' => $statusCode, 'exception' => $exception]);
            }
        }
        $status = $this->response->getStatus();
        return "<html lang='en'><title>$status</title><body>$status</body></html>";
    }
773570
public function display(Exception $exception, $code)
    {
        // Collect some info about the exception.
        $info = $this->info($code, $exception);

        // Is the current request an AJAX request?
        if ((boolean)($this->request instanceof Request && $this->request->wantsJson()) == true) {
            $json_object = (object)[ 'error' => [
                'type'    => 'Exception',
                'message' => $info['message'],
            ] ];

            return JsonResponse::create($json_object, $code);
        }

        // For model-not-found, use 404 errors.
        if ($exception instanceof ModelNotFoundException) {
            $code = 404;
        }

        // If there is a custom view, use that.
        if ($this->view->exists("errors.{$code}")) {
            return $this->view->make("errors.{$code}", $info)->render();
        }

        // If the configured default error view (or errors.error) exists, render that.
        if (($errorview = $this->config->get('view.error', 'errors.error')) && $this->view->exists($errorview)) {
            return $this->view->make($errorview, $info)->render();
        }

        // Last resort: simply show the error code and message.
        return new Response($this->getFallbackDisplay($code, $info['name'], $info['message']), $code);
    }
920663
protected function renderException($request, Exception $e)
    {
        return $this->app[ExceptionHandler::class]->render($request, $e);
    }
739919
protected function renderXmlErrorMessage(Exception $exception)
    {
        $xml = "<error>\n  <message>Slim Application Error</message>\n";
        if ($this->displayErrorDetails) {
            do {
                $xml .= "  <exception>\n";
                $xml .= "    <type>" . get_class($exception) . "</type>\n";
                $xml .= "    <code>" . $exception->getCode() . "</code>\n";
                $xml .= "    <message>" . $this->createCdataSection($exception->getMessage()) . "</message>\n";
                $xml .= "    <file>" . $exception->getFile() . "</file>\n";
                $xml .= "    <line>" . $exception->getLine() . "</line>\n";
                $xml .= "    <trace>" . $this->createCdataSection($exception->getTraceAsString()) . "</trace>\n";
                $xml .= "  </exception>\n";
            } while ($exception = $exception->getPrevious());
        }
        $xml .= "</error>";

        return $xml;
    }
444661
private function httpExceptionResponse(ServerRequestInterface $request, HttpException $exception): ResponseInterface
    {
        if ($request->getHeaderLine('X-Requested-With') !== '') {
            $this->layout = 'layouts/ajax';
        }

        return $this->viewResponse('components/alert-danger', [
            'alert' => $exception->getMessage(),
            'title' => $exception->getMessage(),
        ], $exception->getStatusCode());
    }
972104
public function render($request, Exception $exception)
    {
        $exception = $this->prepareException($exception);

        if ($exception instanceof HttpResponseException) {
            return $exception->getResponse();
        } elseif ($exception instanceof AuthenticationException) {
            return $this->unauthenticated($request, $exception);
        } elseif ($exception instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($exception, $request);
        } elseif ($this->isHttpException($exception) && $this->customErrorHtmlTemplateExists($exception)) {
            return $this->prepareResponse($request, $exception);
        }

        $flattened = FlattenException::create($exception);

        $code = $flattened->getStatusCode();
        $headers = $flattened->getHeaders();
        $response = $this->getContent($exception, $code, $request);

        // If it's already a response, return that.
        if (!$response instanceof BaseResponse) {
            $response = new Response($this->getContent($exception, $code, $request), $code, $headers);
        }

        return $response;
    }
92462
protected function invalidJson($request, ValidationException $exception)
    {
        $jsonResponse = parent::invalidJson($request, $exception);

        $original = (array)$jsonResponse->getData();

        $jsonResponse->setData(array_merge($original, [
            'statusCode' => $exception->status,
            'errors' => Arrays::expandDotNotationKeys((array)$original['errors']),
        ]));

        return $jsonResponse;
    }
186956
public function handleException($exception)
  {
    // Disable error capturing to avoid recursive errors while handling exceptions.
    $this->unregister();

    try
    {
      $this->clearOutput();
      $this->renderException($exception);

      exit(-1);
    }
    catch (\Exception $e)
    {
      // Another exception could be thrown while displaying the exception.
      $message = "An Error occurred while handling another error:\n";
      $message .= (string)$e;
      $message .= "\nPrevious exception:\n";
      $message .= (string)$exception;
      if ($this->myDebug)
      {
        $this->echoMessage($message);
      }
      else
      {
        $this->echoMessage('An internal server error occurred.');
      }
      $message .= "\n\$_SERVER = ".print_r($_SERVER, true);
      error_log($message);

      exit(1);
    }
  }
1128140
public function render($request, Exception $e)
    {
        if (str_is('api.*', $request->getHost())) {
            /** @TODO Really ugly hack to always return JSON for api */
            $request->headers->set('x-requested-with', 'XMLHttpRequest');
        }
        return parent::render($request, $e);
    }
156310
protected function transformException(Exception $exception)
    {
        if (Request::capture()->wantsJson()) {
            $this->transformAuthException($exception);
            $this->transformEloquentException($exception);
            $this->transformValidationException($exception);
        }
    }