Creates ApiException from any other exception.

@param \Exception $e            The original exception.
@param null       $overrideCode The code to override.

@return static
974972
public static function makeFromException($e, $overrideCode = null)
    {
        $code = $overrideCode === null ? $e->getCode() : $overrideCode;

        if ($e instanceof static) {
            $e->code = $code;

            return $e;
        }

        return new static($e->getMessage(), $code, $e);
    }
1373995
public function getExceptionByCode($code)
    {
        $code       = (int) $code;
        $exceptions = array();
        foreach ($this->_exceptions as $e) {
            if ($code == $e->getCode()) {
                $exceptions[] = $e;
            }
        }

        if (empty($exceptions)) {
            $exceptions = false;
        }

        return $exceptions;
    }
791935
private function generateExceptionResponse($request, Exception $e)
    {
        $formatters = $this->config['formatters'];

        // :: notation will otherwise not work for PHP <= 5.6
        $responseFactoryClass = $this->config['response_factory'];

        // Allow users to have a base formatter for every response.
        $response = $responseFactoryClass::make($e);

        foreach($formatters as $exceptionType => $formatter) {
            if (!($e instanceof $exceptionType)) {
                continue;
            }

            if (
                !class_exists($formatter) ||
                !(new ReflectionClass($formatter))->isSubclassOf(new ReflectionClass(BaseFormatter::class))
            ) {
                throw new InvalidArgumentException(
                    sprintf(
                        "%s is not a valid formatter class.",
                        $formatter
                    )
                );
            }

            $formatterInstance = new $formatter($this->config, $this->debug);
            $formatterInstance->format($response, $e, $this->reportResponses);

            break;
        }

        return $response;
    }
63891
protected function transformMediaUploadException(Exception $e)
    {
        if ($e instanceof MediaUploadException) {
            $status_code = $this->getStatusCodeForMediaUploadException($e);
            return new HttpException($status_code, $e->getMessage(), $e);
        }

        return $e;
    }
63086
public function exceptionEditAction($code)
    {
        $cms = $this->getCmsManager();

        if (!$this->getExceptionListener()->hasErrorCode($code)) {
            throw new InternalErrorException(sprintf('The error code "%s" is not set in the configuration', $code));
        }

        try {
            $page = $this->getExceptionListener()->getErrorCodePage($code);
        } catch (PageNotFoundException $e) {
            throw new InternalErrorException('The requested error page does not exist, please run the sonata:page:update-core-routes command', null, $e);
        }

        $cms->setCurrentPage($page);

        // NEXT_MAJOR: remove the usage of $this->getRequestObject() by injecting the request action method in 4.0 (BC break)
        return $this->getPageServiceManager()->execute($page, $this->getRequestObject());
    }
476609
public static function create(int $code = 500, array $context = [], Throwable $previous = null): self
    {
        if (!isset(self::$phrases[$code])) {
            throw new RuntimeException("Http error not valid ({$code})");
        }

        $exception = new static(self::$phrases[$code], $code, $previous);
        $exception->setContext($context);

        return $exception;
    }
1079083
public static function exception(Exception $e, $httpCode = 500, $headers = NULL)
	{
		if ($e instanceof HTTP_Exception_Redirect) throw $e;
		if ($e instanceof HTTP_Exception) $httpCode = $e->getCode() ;

		self::json(Helpers_Exception::toArray($e), $httpCode, $headers);
	}
397084
protected function convertExceptionToResponse(Exception $e)
    {
        $e = FlattenException::create($e);

        $handler = new SymfonyExceptionHandler(config('app.debug'));

        $decorated = $this->decorate($handler->getContent($e), $handler->getStylesheet($e));

        return SymfonyResponse::create($decorated, $e->getStatusCode(), $e->getHeaders());
    }
1297902
private function handleException($e)
    {
        // TODO: test coverage
        if ($e instanceof ClientException) {
            // will catch all 4xx errors
            if ($e->getResponse()->getStatusCode() == 403) {
                throw new AuthenticationException(
                    $this->apiKey,
                    $this->apiSecret,
                    null,
                    $e
                );
            } else {
                throw new DomainException(
                    'The OpenTok API request failed: '. json_decode($e->getResponse()->getBody(true))->message,
                    null,
                    $e
                );
            }
        } else if ($e instanceof ServerException) {
            // will catch all 5xx errors
            throw new UnexpectedValueException(
                'The OpenTok API server responded with an error: ' . json_decode($e->getResponse()->getBody(true))->message,
                null,
                $e
            );
        } else {
            // TODO: check if this works because Exception is an interface not a class
            throw new \Exception('An unexpected error occurred');
        }
    }
347904
protected function convertExceptionToResponse(Exception $e)
    {
        $headers = $this->isHttpException($e) ? $e->getHeaders() : [];
        $statusCode = $this->isHttpException($e) ? $e->getStatusCode() : 500;

        try {
            $content = config('app.debug') && class_exists(Whoops::class)
                ? $this->renderExceptionWithWhoops($e)
                : $this->renderExceptionWithSymfony($e, config('app.debug'));
        } catch (Exception $e) {
            $content = $content ?? $this->renderExceptionWithSymfony($e, config('app.debug'));
        }

        return SymfonyResponse::create(
            $content,
            $statusCode,
            $headers
        );
    }
1037989
public function onKernelException(GetResponseForExceptionEvent $e)
    {
        if (!$this->enabled) return;

        $req = $e->getRequest();
        $cfg = $req->attributes->get('_ac_web_service');

        //notify of generic API error, return early if a response gets set
        $e->getDispatcher()->dispatch(self::API_EXCEPTION, $e);
        if ($e->getResponse()) {
            return;
        }

        //handle exception body format
        $exception = $e->getException();
        $exceptionClass = get_class($exception);

        //preserve specific http exception codes and messages, otherwise it's 500
        $realHttpErrorCode = $outgoingHttpStatusCode = 500;
        $errorMessage = "Internal Server Error";
        if ($exception instanceof ServiceException) {
            $errorData = $exception->getData();
        }
        if ($exception instanceof HttpException) {
            $realHttpErrorCode = $outgoingHttpStatusCode = $exception->getStatusCode();
            $errorMessage = ($exception->getMessage()) ? $exception->getMessage() : Response::$statusTexts[$realHttpErrorCode];
        } elseif (isset($cfg['http_exception_map'][$exceptionClass])) {
            //check exception map for overrides
            $map = $cfg['http_exception_map'];
            $realHttpErrorCode = $outgoingHttpStatusCode = $map[$exceptionClass]['code'];
            $errorMessage =
                (isset($map[$exceptionClass]['message']))
                ? $map[$exceptionClass]['message']
                : Response::$statusTexts[$realHttpErrorCode];
        }

        //set generic error data
        if (!isset ($errorData)) {
            $errorData = [];
        }
        $errorData['response'] = [
            'code' => $realHttpErrorCode,
            'message' => $errorMessage,
        ];

        //inject exception data if configured to do so
        if ($cfg['include_exception_data']) {
            $errorData['exception'] = array(
                'class' => get_class($exception),
                'message' => $exception->getMessage(),
                'code' => $exception->getCode(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => explode("\n", ImprovedStackTrace::getTrace($exception)),
            );
        }

        //serialize error content into requested format, if format is not supported by the serializer, do json
        //TODO: consider support for exception template formats
        $format = isset($cfg['http_response_format']) ? $cfg['http_response_format'] : $cfg['default_response_format'];
        $format = (in_array($format, $this->serializableFormats)) ? $format : 'json';
        $content = $this->container->get('serializer')->serialize($errorData, $format);

        //check for code suppression
        if ($cfg['suppress_response_codes']) {
            $outgoingHttpStatusCode = 200;
        }

        //log the exception
        $logLevel = $realHttpErrorCode >= 500 ? 'error' : 'warning';
        $logMessage =
            "Caught exception (mapped to code $realHttpErrorCode), " .
            "response to client becomes HTTP $outgoingHttpStatusCode $errorMessage\n" .
            ImprovedStackTrace::getTrace($exception) . "\n---";
        $this->logger->log($logLevel, $logMessage);

        $headers = array_merge($cfg['additional_headers'], $this->formatHeaders[$format]);

        //set response
        $e->setResponse(new Response($content, $outgoingHttpStatusCode, $headers));
    }
1332229
public function exception(\Exception $e)
    {
        $fields = [];

        $addToField = function($name, $value, $short = false) use (&$fields) {
            if (!empty($value)) {
                $fields[] = [
                    'title' => $name,
                    'value' => $value,
                    'short' => $short,
                ];
            }
        };

        $addToField('Environment', app()->environment(), true);
        $addToField('Exception', get_class($e), true);
        $addToField(
            'Http code',
            $e instanceof \Symfony\Component\HttpKernel\Exception\HttpException ? $e->getStatusCode() : 500,
            true
        );
        $addToField('Code', $e->getCode(), true);
        $addToField('File', $e->getFile(), true);
        $addToField('Line', $e->getLine(), true);
        $addToField('Request url', request()->url(), true);
        $addToField('Request method', request()->method(), true);
        $addToField('Request param', json_encode(request()->all()), true);

        $message    = ':bug: Error Occurs on '.app()->environment();
        $type       = 'serious-alert';
        $pretext    = 'Error Occurs on '.app()->environment();
        $attachment = [
            'color'    => 'danger',
            'title'    => $e->getMessage(),
            'fallback' => !empty($e->getMessage()) ? $e->getMessage() : get_class($e),
            'pretext'  => $pretext,
            'fields'   => $fields,
            'text'     => $e->getTraceAsString(),
        ];

        // notify to slack
        $this->post($message, $type, $attachment);
    }
25028
protected function returnException(Exception $e)
    {
        $key = snake_case(class_basename($e));
        $message = $this->translate($key, $e->getMessage());

        return new ExceptionReply($message, [], $e);
    }
840203
public static function exceptionHandler($e)
    {

        $message = 'Code: ' . $e->getCode() . "\n" .
                'Path: ' . \sb\Gateway::$request->path . "\n" .
                'Message: ' . $e->getMessage() . "\n" .
                'Location: ' . $e->getFile() . "\n" .
                'Line: ' . $e->getLine() . "\n";
                if(isset(\sb\Gateway::$request)){
                    $message .= 'Request: '.\sb\Gateway::$request->request."\n";
                    if(isset(\sb\Gateway::$request->method)){
                        $message .= 'Method: '.\sb\Gateway::$request->method."\n";
                    }
                    
                    if(count(\sb\Gateway::$request->get)){
                        $message .= 'Get: '.http_build_query(\sb\Gateway::$request->get) ."\n";
                    }
                }

        if (self::$show_trace) {
            $message .= "Trace: \n\t" . str_replace("\n", "\n\t", \print_r($e->getTrace(), 1));
        }

        if (\method_exists("\App", "exception_handler")) {
            if (\App::exceptionHandler($e, $message) === false) {
                return false;
            }
        }

        if (\ini_get("display_errors") == true) {
            if (\sb\Gateway::$command_line) {
                \file_put_contents('php://stderr', "\n" . $message  . "\n");
            } else {
                echo '<pre style="background-color:red;padding:10px;color:#FFF;">' . $message . '</pre>';
            }
        }

        if (!isset(\App::$logger)) {
            \App::$logger = new \sb\Logger\FileSystem();
        }

        \App::$logger->exceptions($message);

    }
85893
final protected function createApiException(ResponseInterface $response, $data, $code = null, $message = null)
    {
        $e = new ApiException(get_class($this).' #'.$code.': '.$message);
        $e->setResponse($response);
        $e->setData($data);
        $e->setErrorCode($code);
        $e->setErrorMessage($message);

        return $e;
    }
941584
public function fromException(\Exception $e)
    {
        return new Error(E_EXCEPTION, $e->__toString(), $e->getFile(), $e->getLine(), $e->getCode());
    }
589872
public static function exception($title, PhpException $e)
    {
        $exceptionMessage = (string) $e->getMessage();

        $content = (string) $title . PHP_EOL . 'Exception of type \'' . get_class($e) . '\': ' . $exceptionMessage;

        // need to add check if the log verbosity is info or debug. Look at old code
        self::$logger->exception(new PhpException($content, null, $e));

        return true;
    }