/**
  * @return int
  */
 protected function getExceptionStatusCode()
 {
     if ($this->exception instanceof HttpException) {
         return $this->exception->getStatusCode();
     } elseif (array_key_exists($this->exception->getCode(), Response::$statusTexts) && $this->exception->getCode() >= Response::HTTP_BAD_REQUEST) {
         return $this->exception->getCode();
     }
     return Response::HTTP_INTERNAL_SERVER_ERROR;
 }
Пример #2
0
 /**
  * {@inheritdoc}
  */
 public function getHttpException()
 {
     $code = 500;
     $message = '';
     if (!$this->isProd()) {
         $message = $this->currentException->getMessage() . '<pre>' . $this->currentException->getTraceAsString() . '</pre>';
     }
     if ($this->currentException instanceof HttpException) {
         $code = $this->currentException->getStatusCode();
     }
     return new HttpException($code, $message, $this->currentException);
 }
 /**
  * @return int
  */
 protected function getExceptionStatusCode()
 {
     if ($this->exception instanceof HttpException) {
         return $this->exception->getStatusCode();
     }
     if ($this->exception instanceof AbstractValidationException) {
         return Response::HTTP_BAD_REQUEST;
     }
     if ($this->isValidHttpStatusCode($this->exception->getCode())) {
         return $this->exception->getCode();
     }
     return Response::HTTP_INTERNAL_SERVER_ERROR;
 }
 /**
  * @return mixed
  */
 public function getStatusCode()
 {
     if (isset($this->exception)) {
         if ($this->exception instanceof HttpException) {
             return $this->exception->getStatusCode();
         } elseif (array_key_exists($this->exception->getCode(), Response::$statusTexts) && $this->exception->getCode() >= 400) {
             return $this->exception->getCode();
         } else {
             return Response::HTTP_INTERNAL_SERVER_ERROR;
         }
     }
     return $this->statusCode;
 }
Пример #5
0
 /**
  * Return an error into an HTTP or JSON data array.
  *
  * @param string $title
  * @return array
  */
 public function error($title = null)
 {
     if ($title == null) {
         $title = $this->debug ? 'The application could not run because of the following error:' : 'A website error has occurred. Sorry for the temporary inconvenience.';
     }
     $type = $this->request->getHeader('Content-Type');
     $mesg = $this->exception->getMessage();
     $file = $this->exception->getFile();
     $line = $this->exception->getLine();
     $code = $this->exception->getCode();
     $statusCode = method_exists($this->exception, 'getStatusCode') ? $this->exception->getStatusCode() : null;
     // Check status code is null
     if ($statusCode == null) {
         $statusCode = $code >= 100 && $code <= 500 ? $code : 400;
     }
     $this->response->withStatus($statusCode);
     // Check logger exist
     if ($this->logger !== null) {
         // Send error to log
         $this->logger->addError($this->exception->getMessage());
     }
     $this->isJson = isset($type[0]) && $type[0] == 'application/json';
     // Check content-type is application/json
     if ($this->isJson) {
         // Define content-type to json
         $this->response->withHeader('Content-Type', 'application/json');
         $error = ['status' => 'error', 'status_code' => $statusCode, 'error' => $title, 'details' => []];
         // Check debug
         if ($this->debug) {
             $error['details'] = ['message' => $mesg, 'file' => $file, 'line' => $line, 'code' => $code];
         }
         return $error;
     }
     // Define content-type to html
     $this->response->withHeader('Content-Type', 'text/html');
     $message = sprintf('<span>%s</span>', htmlentities($mesg));
     $error = ['type' => get_class($this->exception), $error['status_code'] = $statusCode, 'message' => $message];
     // Check debug
     if ($this->debug) {
         $trace = $this->exception->getTraceAsString();
         $trace = sprintf('<pre>%s</pre>', htmlentities($trace));
         $error['file'] = $file;
         $error['line'] = $line;
         $error['code'] = $code;
         $error['trace'] = $trace;
     }
     $error['debug'] = $this->debug;
     $error['title'] = $title;
     return $error;
 }
Пример #6
0
    /**
     * Creates the error Response associated with the given Exception.
     *
     * @param \Exception $exception An \Exception instance
     *
     * @return Response A Response instance
     */
    public function createResponse(\Exception $exception)
    {
        $content = '';
        $title = '';
        try {
            $code = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;
            $exception = FlattenException::create($exception);

            switch($code) {
                case 404:
                    $title = 'Sorry, the page you are looking for could not be found.';
                    break;
                default:
                    $title = 'Whoops, looks like something went wrong.';
            }

            if ($this->debug) {
                $content = $this->getContent($exception);
            }
        } catch (\Exception $e) {
            // something nasty happened and we cannot throw an exception here anymore
            if ($this->debug) {
                $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($exception), $exception->getMessage());
            } else {
                $title = 'Whoops, looks like something went wrong.';
            }
        }

        return new Response($this->decorate($content, $title), $code);
    }
Пример #7
0
    public static function create(\Exception $exception, $statusCode = null, array $headers = array())
    {
        $e = new static();
        $e->setMessage($exception->getMessage());
        $e->setCode($exception->getCode());

        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $exception->getStatusCode();
            $headers = array_merge($headers, $exception->getHeaders());
        } elseif ($exception instanceof RequestExceptionInterface) {
            $statusCode = 400;
        }

        if (null === $statusCode) {
            $statusCode = 500;
        }

        $e->setStatusCode($statusCode);
        $e->setHeaders($headers);
        $e->setTraceFromException($exception);
        $e->setClass(get_class($exception));
        $e->setFile($exception->getFile());
        $e->setLine($exception->getLine());

        $previous = $exception->getPrevious();

        if ($previous instanceof \Exception) {
            $e->setPrevious(static::create($previous));
        } elseif ($previous instanceof \Throwable) {
            $e->setPrevious(static::create(new FatalThrowableError($previous)));
        }

        return $e;
    }
Пример #8
0
    public static function create(\Exception $exception, $statusCode = null, array $headers = array())
    {
        $e = new static();
        $e->setMessage($exception->getMessage());
        $e->setCode($exception->getCode());

        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $exception->getStatusCode();
            $headers = array_merge($headers, $exception->getHeaders());
        }

        if (null === $statusCode) {
            $statusCode = 500;
        }

        $e->setStatusCode($statusCode);
        $e->setHeaders($headers);
        $e->setTrace($exception->getTrace(), $exception->getFile(), $exception->getLine());
        $e->setClass(get_class($exception));
        $e->setFile($exception->getFile());
        $e->setLine($exception->getLine());
        if ($exception->getPrevious()) {
            $e->setPrevious(static::create($exception->getPrevious()));
        }

        return $e;
    }
 /**
  * Echoes an exception for the web.
  *
  * @param \Exception $exception The exception
  * @return void
  */
 protected function echoExceptionWeb(\Exception $exception)
 {
     if ($exception instanceof Exception) {
         $statusCode = 400;
         $json = ['status' => 'invalid_request', 'reason' => $exception->getMessage()];
     } elseif ($exception instanceof \TYPO3\Flow\Security\Exception) {
         $statusCode = 403;
         $json = ['status' => 'unauthorized', 'reason' => $exception->getMessage()];
     } else {
         $statusCode = 500;
         if ($exception instanceof FlowException) {
             $statusCode = $exception->getStatusCode();
         }
         $json = ['status' => 'error', 'reason' => $exception->getMessage(), 'errorClass' => get_class($exception)];
     }
     if ($exception->getPrevious() !== NULL) {
         $json['previous'] = $exception->getPrevious()->getMessage();
     }
     $json['stacktrace'] = explode("\n", $exception->getTraceAsString());
     $statusMessage = Response::getStatusMessageByCode($statusCode);
     if (!headers_sent()) {
         header(sprintf('HTTP/1.1 %s %s', $statusCode, $statusMessage));
         header('Content-Type: application/json');
     }
     print json_encode($json);
 }
Пример #10
0
 /**
  * Render an exception using ErrorController.
  *
  * @param \Exception $e
  *
  * @return \Illuminate\Http\Response
  */
 protected function renderControllerException(\Exception $e)
 {
     $code = 500;
     if ($e instanceof HttpResponseException) {
         $code = $e->getStatusCode();
     } else {
         if ($e->getCode() > 0) {
             $code = $e->getCode();
         }
     }
     try {
         /** @var ErrorController $controller */
         $controller = app()->make(ErrorController::class);
         if (method_exists($controller, 'error' . $code)) {
             $action = 'error' . $code;
         } else {
             $action = 'errorDefault';
         }
         $response = $controller->callAction($action, [$e]);
         if (!$response instanceof Response) {
             $response = new Response($response);
         }
         return $this->toIlluminateResponse($response, $e);
     } catch (\Exception $ex) {
         return $this->toIlluminateResponse($this->convertExceptionToResponse($ex), $ex);
     }
 }
 /**
  * @param \Exception $exception
  * @return \Illuminate\Http\JsonResponse
  */
 public function format($exception)
 {
     // Define the response
     $result = ['errors' => trans('messages.sorry')];
     // Default response of 400
     $statusCode = 400;
     $addDebugData = $this->isDebugEnabled();
     switch (true) {
         case $exception instanceof HttpException:
             $statusCode = $exception->getStatusCode();
             $result['errors'] = $exception->getMessage();
             break;
         case $exception instanceof ValidationException:
             $result['errors'] = $exception->errors();
             $addDebugData = false;
             break;
     }
     // Prepare response
     $response = ['success' => false, 'result' => $result, 'meta' => ['version' => config('app.version.api'), 'request' => \Request::method() . ' ' . \Request::url(), 'debug' => $this->isDebugEnabled()]];
     // If the app is in debug mode && not Validation exception
     if ($addDebugData) {
         $response['debug'] = ['exception' => get_class($exception), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTrace()];
     }
     // Return a JSON response with the response array and status code
     return response()->json($response, $statusCode);
 }
Пример #12
0
 public function testInstantiation()
 {
     $exception = new Exception('test message', 9, 201, [1, 2, 3]);
     $this->assertEquals('test message', $exception->getMessage());
     $this->assertEquals(9, $exception->getCode());
     $this->assertEquals(201, $exception->getStatusCode());
     $this->assertEquals([1, 2, 3], $exception->getDetails());
 }
Пример #13
0
 /**
  * Handle errors thrown in the application.
  *
  * @todo: according to the docs of flint it should handle exceptions, but for some reason it doesn't seem to work.
  *
  * @param  \Exception $exception
  * @return Response
  */
 public function errorHandler(\Exception $exception)
 {
     if ($exception instanceof HttpException && $exception->getStatusCode() == 404) {
         $template = 'error.404.html.twig';
     } else {
         $template = 'error.html.twig';
     }
     return $this['twig']->render($template);
 }
Пример #14
0
 /**
  * Logs an exception.
  *
  * @param \Exception $exception The \Exception instance
  * @param string $message The error message to log
  */
 protected function logException(\Exception $exception, $message)
 {
     if (null !== $this->logger) {
         if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
             $this->logger->critical($message, array('exception' => $exception));
         } else {
             $this->logger->error($message, array('exception' => $exception));
         }
     }
 }
Пример #15
0
 private static function extractStatus(\Exception $exception)
 {
     if ($exception instanceof HttpExceptionInterface) {
         return $exception->getStatusCode();
     }
     if ($exception instanceof \Symfony\Component\Security\Core\Exception\AccessDeniedException) {
         return 403;
     }
     return 500;
 }
Пример #16
0
 /**
  * {@inheritdoc}
  */
 protected function logException(\Exception $exception, $message, $original = true)
 {
     if (null !== $this->logger) {
         /** @var BaseException $exception */
         if ($exception->getStatusCode() >= 500) {
             $this->logger->critical($message, array('exception' => $exception));
         } else {
             $this->logger->error($message, array('exception' => $exception));
         }
     }
 }
Пример #17
0
 /**
  * Checks if the exception implements the HttpExceptionInterface, or returns
  * as generic 500 error code for a server side error.
  * @param \Exception $exception
  * @return int
  */
 protected function getStatusCode($exception)
 {
     if ($exception instanceof HttpExceptionInterface) {
         $code = $exception->getStatusCode();
     } elseif ($exception instanceof AjaxException) {
         $code = 406;
     } else {
         $code = 500;
     }
     return $code;
 }
 /**
  * @param \Exception $exception
  * @return array
  */
 public function transformException(\Exception $exception)
 {
     $data = array('code' => sprintf('%d', $exception->getCode()), 'title' => $exception->getMessage());
     if ($exception instanceof HttpException) {
         $data['status'] = (string) $exception->getStatusCode();
     }
     if ($this->debug) {
         $data['meta'] = array('trace' => $exception->getTraceAsString(), 'file' => $exception->getFile(), 'line' => $exception->getLine());
     }
     return array('errors' => array($data));
 }
 public function onEventException(Application $app, \Exception $e)
 {
     $response = $app->response('', 500);
     if ($e instanceof HttpException) {
         $response->setStatusCode($e->getStatusCode());
     }
     if ($app->getParameter('debug')) {
         $response->setContent($this->prettyException($e));
     }
     $app->setResponse($response);
 }
 /**
  * {@inheritdoc}
  */
 public function createErrorResponseByException(\Exception $ex = null)
 {
     //TODO - handle more content types
     if (null !== $ex && $ex instanceof HttpExceptionInterface) {
         $statusCode = $ex->getStatusCode();
         $headers = (array) $ex->getHeaders();
     } else {
         $statusCode = 500;
         $headers = array('Content-Type' => array('text/html; charset=UTF-8'), 'Cache-Control' => array('max-age=0', 'must-revalidate', 'no-cache', 'no-store', 'private'));
     }
     return $this->messageFactory->createResponse($this->errorPageLoader->loadContentByStatusCode($statusCode), $statusCode, $headers);
 }
Пример #21
0
 /**
  * Logs an exception.
  *
  * @param \Exception $exception The original \Exception instance
  * @param string     $message   The error message to log
  * @param Boolean    $original  False when the handling of the exception thrown another exception
  */
 protected function logException(\Exception $exception, $message, $original = true)
 {
     $isCritical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;
     if (null !== $this->logger) {
         if ($isCritical) {
             $this->logger->critical($message);
         } else {
             $this->logger->error($message);
         }
     } elseif (!$original || $isCritical) {
         error_log($message);
     }
 }
Пример #22
0
 /**
  * @param \Exception $exception
  * @param string     $message
  * @param bool       $original
  */
 protected function logException(\Exception $exception, $message, $original = true)
 {
     $isCritical = !$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500;
     $context = array('exception' => $exception);
     if (null !== $this->logger) {
         if ($isCritical) {
             $this->logger->critical($message, $context);
         } else {
             if (!$exception instanceof NotFoundHttpException && !$exception instanceof BadRequestHttpException) {
                 $this->logger->error($message, $context);
             }
         }
     } elseif (!$original || $isCritical) {
         error_log($message);
     }
 }
 /**
  * Formats and echoes the exception as XHTML.
  *
  * @param \Exception $exception The exception object
  * @return void
  */
 protected function echoExceptionWeb(\Exception $exception)
 {
     $statusCode = 500;
     if ($exception instanceof FlowException) {
         $statusCode = $exception->getStatusCode();
     }
     $statusMessage = Response::getStatusMessageByCode($statusCode);
     if (!headers_sent()) {
         header(sprintf('HTTP/1.1 %s %s', $statusCode, $statusMessage));
     }
     if (isset($this->renderingOptions['templatePathAndFilename'])) {
         echo $this->buildCustomFluidView($exception, $this->renderingOptions)->render();
     } else {
         $this->renderStatically($statusCode, $exception);
     }
 }
 /**
  * Echoes an exception for the web.
  *
  * @param \Exception $exception The exception
  * @return void
  */
 protected function echoExceptionWeb(\Exception $exception)
 {
     $statusCode = 500;
     if ($exception instanceof FlowException) {
         $statusCode = $exception->getStatusCode();
     }
     $statusMessage = Response::getStatusMessageByCode($statusCode);
     $referenceCode = $exception instanceof FlowException ? $exception->getReferenceCode() : null;
     if (!headers_sent()) {
         header(sprintf('HTTP/1.1 %s %s', $statusCode, $statusMessage));
     }
     try {
         if (isset($this->renderingOptions['templatePathAndFilename'])) {
             echo $this->buildCustomFluidView($exception, $this->renderingOptions)->render();
         } else {
             echo $this->renderStatically($statusCode, $referenceCode);
         }
     } catch (\Exception $innerException) {
         $this->systemLogger->logException($innerException);
     }
 }
 /**
  * Echoes an exception for the web.
  *
  * @param \Exception $exception The exception
  * @return void
  */
 protected function echoExceptionWeb(\Exception $exception)
 {
     if ($exception instanceof Exception) {
         $statusCode = 400;
         $json = ['status' => 'invalid_request'];
     } elseif ($exception instanceof \TYPO3\Flow\Security\Exception) {
         $statusCode = 403;
         $json = ['status' => 'unauthorized'];
     } else {
         $statusCode = 500;
         if ($exception instanceof FlowException) {
             $statusCode = $exception->getStatusCode();
         }
         $json = ['status' => 'error'];
     }
     $statusMessage = Response::getStatusMessageByCode($statusCode);
     if (!headers_sent()) {
         header(sprintf('HTTP/1.1 %s %s', $statusCode, $statusMessage));
         header('Content-Type: application/json');
     }
     print json_encode($json);
 }
Пример #26
0
 /**
  * create response
  * with a HttpException status code and headers are considered
  * other exceptions default to status code 500
  * a error_docs/error_{status_code}.php template is parsed, when found
  * otherwise the exception data is decorated and dumped
  * 
  * @param \Exception $e
  * @return \vxPHP\Http\Response
  */
 protected function createResponse(\Exception $e)
 {
     if ($e instanceof HttpException) {
         $status = $e->getStatusCode();
         $headers = $e->getHeaders();
     } else {
         $status = Response::HTTP_INTERNAL_SERVER_ERROR;
         $headers = array();
     }
     $config = Application::getInstance()->getConfig();
     if (isset($config->paths['tpl_path'])) {
         $path = ($config->paths['tpl_path']['absolute'] ? '' : rtrim(Application::getInstance()->getRootPath(), DIRECTORY_SEPARATOR)) . $config->paths['tpl_path']['subdir'];
         if (file_exists($path . 'error_docs' . DIRECTORY_SEPARATOR . 'error_' . $status . '.php')) {
             $tpl = SimpleTemplate::create('error_docs' . DIRECTORY_SEPARATOR . 'error_' . $status . '.php');
             $content = $tpl->assign('exception', $e)->assign('status', $status)->display();
         } else {
             $content = $this->decorateException($e, $status);
         }
     } else {
         $content = $this->decorateException($e, $status);
     }
     return new Response($content, $status, $headers);
 }
 public static function create(\Exception $exception, $statusCode = null, array $headers = array())
 {
     $e = new static();
     $e->setMessage($exception->getMessage());
     $e->setCode($exception->getCode());
     if ($exception instanceof HttpExceptionInterface) {
         //TODO: Despues quitar la dependencia a esta excepcion de symfony
         $statusCode = $exception->getStatusCode();
         $headers = array_merge($headers, $exception->getHeaders());
     }
     if (null === $statusCode) {
         $statusCode = 500;
     }
     $e->setStatusCode($statusCode);
     $e->setHeaders($headers);
     $e->setTraceFromException($exception);
     $e->setClass(get_class($exception));
     $e->setFile($exception->getFile());
     $e->setLine($exception->getLine());
     if ($exception->getPrevious()) {
         $e->setPrevious(static::create($exception->getPrevious()));
     }
     return $e;
 }
Пример #28
0
 /**
  * Error handler
  * 
  * @param \Exception $exc
  * @return string 
  */
 private function _errorHandler(\Exception $exc)
 {
     $results = array();
     $httpCodes = $this->app["my"]->get('http')->getHttpCodes();
     //--------------------
     // Prepary output data
     if ($exc instanceof Exception\HttpException) {
         $code = (int) $exc->getStatusCode();
         if (isset($httpCodes[$code])) {
             $code .= " {$httpCodes[$code]}";
         }
     } else {
         $code = $exc->getCode();
     }
     $results["code"] = $code;
     $results["message"] = $exc->getMessage();
     // Save results
     $this->saveResults($results, false);
     // Output error to log
     $this->saveErrorLog($results);
     $message = $this->showResults($results, false);
     return $message;
 }
 /**
  * Returns the status code for an exception.
  *
  * @param \Exception $exception The exception
  *
  * @return int The status code
  */
 private function getStatusCodeForException(\Exception $exception)
 {
     return $exception instanceof HttpException ? $exception->getStatusCode() : 500;
 }
Пример #30
0
 /**
  * Converts an exception into a response.
  *
  * @param \Exception $e
  *   An exception
  * @param Request $request
  *   A Request instance
  * @param int $type
  *   The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
  *   HttpKernelInterface::SUB_REQUEST)
  *
  * @return Response
  *   A Response instance
  *
  * @throws \Exception
  *   If the passed in exception cannot be turned into a response.
  */
 protected function handleException(\Exception $e, $request, $type)
 {
     if ($e instanceof HttpExceptionInterface) {
         $response = new Response($e->getMessage(), $e->getStatusCode());
         $response->headers->add($e->getHeaders());
         return $response;
     } else {
         throw $e;
     }
 }