当前位置: 首页>>代码示例>>PHP>>正文


PHP Exception类代码示例

本文整理汇总了PHP中Exception的典型用法代码示例。如果您正苦于以下问题:PHP Exception类的具体用法?PHP Exception怎么用?PHP Exception使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Exception类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: exception

 public static function exception(Exception $e)
 {
     $code = $e->getCode();
     $message = $e->getMessage();
     switch (self::$_CODE[$code]) {
         case 'DATA_NOT_FOUND':
             self::_dataNotFound($message);
             break;
         case 'CLASS_NOT_FOUND':
             self::_classNotFound($message);
             break;
         case 'METHOD_NOT_FOUND':
             self::_methodNotFound($message);
             break;
         case 'FILE_NOT_FOUND':
             self::_fileNotFound($message);
             break;
         case 'DIRECTORY_NOT_FOUND':
             self::_directoryNotFound($message);
             break;
         case 'SERVER_OVERLOADING':
             self::_serverOverloading($message);
             break;
         default:
             self::_dataNotFound($message);
             break;
             exit;
     }
 }
开发者ID:piratevn,项目名称:cms-gio,代码行数:29,代码来源:Exception.php

示例2: __construct

 public function __construct($message = '', $code = 0, Exception $e = null)
 {
     if ($e && 0 === $code) {
         $code = $e->getCode();
     }
     parent::__construct($message, $code, $e);
 }
开发者ID:netixx,项目名称:Stock,代码行数:7,代码来源:Exception.php

示例3: getExceptionTraceAsString

 /**
  * @param \Exception $exception
  * @return string
  * @todo Fix this to get full stack trace
  */
 public static function getExceptionTraceAsString(\Exception $exception)
 {
     $ret = "";
     $count = 0;
     foreach ($exception->getTrace() as $trace) {
         $args = "";
         if (isset($trace['args'])) {
             $args = array();
             foreach ($trace['args'] as $arg) {
                 if (is_string($arg)) {
                     $args[] = "'" . $arg . "'";
                 } elseif (is_array($arg)) {
                     $args[] = "Array";
                 } elseif (is_null($arg)) {
                     $args[] = 'NULL';
                 } elseif (is_bool($arg)) {
                     $args[] = $arg ? "true" : "false";
                 } elseif (is_object($arg)) {
                     $args[] = get_class($arg);
                 } elseif (is_resource($arg)) {
                     $args[] = get_resource_type($arg);
                 } else {
                     $args[] = $arg;
                 }
             }
             $args = join(", ", $args);
         }
         $ret .= sprintf("#%s %s(%s): %s(%s)\n", $count, isset($trace['file']) ? $trace['file'] : 'unknown file', isset($trace['line']) ? $trace['line'] : 'unknown line', isset($trace['class']) ? $trace['class'] . $trace['type'] . $trace['function'] : $trace['function'], $args);
         $count++;
     }
     return $ret;
 }
开发者ID:jakubpas,项目名称:error-exception,代码行数:37,代码来源:Handler.php

示例4: exceptionHandle

 public static function exceptionHandle(Exception $exception)
 {
     if (DEBUG_MODE) {
         //直接输出调试信息
         echo nl2br($exception->__toString());
         echo '<hr /><p>Router:</p><pre>';
         print_r(Singleton::getInstance('Router'));
         echo '</pre>';
     } else {
         $code = $exception->getCode();
         $message = nl2br($exception->getMessage());
         /*
                     如果错误码"可能为"合法的http状态码则尝试设置,
                     setStatus()方法会忽略非法的http状态码. */
         if ($code >= 400 && $code <= 505 && !headers_sent()) {
             ResponseModule::setStatus($code);
         }
         $var_list = array('message' => $message, 'code' => $code, 'file' => $exception->getFile(), 'url' => Singleton::getInstance('Router')->getUrl());
         if ($error_file = self::_getErrorFilePath($code)) {
             Lugit::$view = new View($var_list);
             Lugit::$view->render($error_file);
         } else {
             echo 'No error page is found.<pre>';
             print_r($var_list);
             echo '</pre>';
         }
     }
     exit;
 }
开发者ID:sujinw,项目名称:php-lugit-framework,代码行数:29,代码来源:Basic.php

示例5: onNotSuccessfulTest

 public function onNotSuccessfulTest(Exception $e)
 {
     if ($e instanceof Horde_Imap_Client_Exception) {
         $e->setMessage($e->getMessage() . ' [' . self::$live->url . ']');
     }
     parent::onNotSuccessfulTest($e);
 }
开发者ID:raz0rsdge,项目名称:horde,代码行数:7,代码来源:Base.php

示例6: ErrorHandler

 /**
  * Error handler which publishes all errors thrown by code which doesn't use
  * structured exception handling
  *
  * @param int $errno
  * @param string $errstr
  * @param string $errfile
  * @param int $errline
  * @param array $errcontext
  */
 public function ErrorHandler($errno, $errstr, $errfile, $errline, array $errcontext)
 {
     $additional_info = array('File' => $errfile, 'Line' => $errline, 'Context' => $errcontext);
     $e = new Exception($errstr, $errno);
     switch ($e->getCode()) {
         # Not serious, ignore
         case E_STRICT:
             break;
             # Not serious, log and carry on unless on a WordPress page.
             # WordPress developers don't fix these, so if this is a WordPress page ignore it.
         # Not serious, log and carry on unless on a WordPress page.
         # WordPress developers don't fix these, so if this is a WordPress page ignore it.
         case E_NOTICE:
         case E_USER_NOTICE:
             if (!function_exists('wp')) {
                 $this->Publish($e, $additional_info);
             }
             break;
             # Not serious, log and carry on
         # Not serious, log and carry on
         case E_WARNING:
         case E_USER_WARNING:
             $this->Publish($e, $additional_info);
             break;
             # Serious, log and die
         # Serious, log and die
         default:
             $this->Publish($e, $additional_info);
             if (!headers_sent()) {
                 header("HTTP/1.1 500 Internal Server Error");
             }
             die('<p class="validationSummary">Sorry, there\'s a problem with this page. Please try again later.</p>');
     }
 }
开发者ID:stoolball-england,项目名称:stoolball-england-website,代码行数:44,代码来源:exception-manager.class.php

示例7: __construct

 /**
  * @param string     $resource       The resource that could not be imported
  * @param string     $sourceResource The original resource importing the new resource
  * @param int        $code           The error code
  * @param \Exception $previous       A previous exception
  */
 public function __construct($resource, $sourceResource = null, $code = null, $previous = null)
 {
     $message = '';
     if ($previous) {
         // Include the previous exception, to help the user see what might be the underlying cause
         // Trim the trailing period of the previous message. We only want 1 period remove so no rtrim...
         if ('.' === substr($previous->getMessage(), -1)) {
             $trimmedMessage = substr($previous->getMessage(), 0, -1);
             $message .= sprintf('%s', $trimmedMessage) . ' in ';
         } else {
             $message .= sprintf('%s', $previous->getMessage()) . ' in ';
         }
         $message .= $resource . ' ';
         // show tweaked trace to complete the human readable sentence
         if (null === $sourceResource) {
             $message .= sprintf('(which is loaded in resource "%s")', $this->varToString($resource));
         } else {
             $message .= sprintf('(which is being imported from "%s")', $this->varToString($sourceResource));
         }
         $message .= '.';
         // if there's no previous message, present it the default way
     } elseif (null === $sourceResource) {
         $message .= sprintf('Cannot load resource "%s".', $this->varToString($resource));
     } else {
         $message .= sprintf('Cannot import resource "%s" from "%s".', $this->varToString($resource), $this->varToString($sourceResource));
     }
     // Is the resource located inside a bundle?
     if ('@' === $resource[0]) {
         $parts = explode(DIRECTORY_SEPARATOR, $resource);
         $bundle = substr($parts[0], 1);
         $message .= ' ' . sprintf('Make sure the "%s" bundle is correctly registered and loaded in the application kernel class.', $bundle);
     }
     parent::__construct($message, $code, $previous);
 }
开发者ID:tahermarkos,项目名称:Transport,代码行数:40,代码来源:FileLoaderLoadException.php

示例8: format

 /**
  * @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);
 }
开发者ID:xEdelweiss,项目名称:my-perfect-back-end,代码行数:30,代码来源:ExceptionAdapter.php

示例9: createExceptionResponse

 public static function createExceptionResponse(\Exception $ex)
 {
     $response = new Response();
     $response->success = false;
     array_push($response->errors, $ex->getMessage());
     return $response;
 }
开发者ID:rmukras,项目名称:ekda.org,代码行数:7,代码来源:ResponseUtils.php

示例10: getFilteredStacktrace

 /**
  * Filters stack frames from PHPUnit classes.
  *
  * @param  Exception $e
  * @param  boolean   $filterTests
  * @param  boolean   $asString
  * @return string
  */
 public static function getFilteredStacktrace(Exception $e, $filterTests = TRUE, $asString = TRUE)
 {
     if ($asString === TRUE) {
         $filteredStacktrace = '';
     } else {
         $filteredStacktrace = array();
     }
     $groups = array('DEFAULT');
     if (!defined('PHPUNIT_TESTSUITE')) {
         $groups[] = 'PHPUNIT';
     }
     if ($filterTests) {
         $groups[] = 'TESTS';
     }
     if ($e instanceof PHPUnit_Framework_SyntheticError) {
         $eTrace = $e->getSyntheticTrace();
     } else {
         $eTrace = $e->getTrace();
     }
     if (!self::frameExists($eTrace, $e->getFile(), $e->getLine())) {
         array_unshift($eTrace, array('file' => $e->getFile(), 'line' => $e->getLine()));
     }
     foreach ($eTrace as $frame) {
         if (isset($frame['file']) && is_file($frame['file']) && !PHP_CodeCoverage::getInstance()->filter()->isFiltered($frame['file'], $groups, TRUE)) {
             if ($asString === TRUE) {
                 $filteredStacktrace .= sprintf("%s:%s\n", $frame['file'], isset($frame['line']) ? $frame['line'] : '?');
             } else {
                 $filteredStacktrace[] = $frame;
             }
         }
     }
     return $filteredStacktrace;
 }
开发者ID:KnpLabs,项目名称:phpunit-easyinstall,代码行数:41,代码来源:Filter.php

示例11: generateErrorForException

 private function generateErrorForException(\Exception $exception)
 {
     if ($exception instanceof CommandInvalidException) {
         $formError = $exception->getForm()->getErrors(true)->current();
         $path = $formError->getOrigin()->getPropertyPath();
         if ($path !== null) {
             // We got PropertyPathInterface or maybe even a string (undocumented).
             $path = (string) $path;
         }
         return new E\Api\BadRequest($formError->getMessage(), $path);
     } elseif ($exception instanceof ConstraintViolationException) {
         return $exception->getError();
     } elseif ($exception instanceof UsernameNotFoundException) {
         return new E\Security\BadCredentials();
     } elseif ($exception instanceof AccessDeniedException) {
         $token = $this->tokenStorage->getToken();
         if ($token && $this->tokenStorage->getToken()->getRoles()) {
             return new E\Security\NotAuthorized();
         } else {
             return new E\Security\NotAuthenticated();
         }
     } elseif ($exception instanceof ProtocolException) {
         return $this->getErrorForOxygenProtocolException($exception);
     } else {
         return new E\Api\UnexpectedError();
     }
 }
开发者ID:Briareos,项目名称:Undine,代码行数:27,代码来源:ErrorFactory.php

示例12: catchExceptions

/**
 * Catch Exceptions
 * @param Exception $err
 */
function catchExceptions($err)
{
    global $config;
    echo "Error with your request!  Please try again later.  " . "If the problem persists contact <a href=\"" . $config['contact'] . "\">" . $config['contact'] . "</a>.";
    error_log($err->__toString(), 0);
    exit(1);
}
开发者ID:jb376,项目名称:netstat_php,代码行数:11,代码来源:netstat.php

示例13: drop

function drop()
{
    call_user_func_array("var_dump", func_get_args());
    $e = new Exception();
    echo "-------\nDump trace: \n" . $e->getTraceAsString() . "\n";
    exit;
}
开发者ID:php-ion,项目名称:php-ion,代码行数:7,代码来源:bootstrap.php

示例14: serverErrorHandler

 /**
  * Log errors.
  *
  * @param \Exception $e
  * @param $serverName
  * @param $type
  * @return string
  */
 protected function serverErrorHandler(\Exception $e, $serverName, $type)
 {
     $errorMessage = "Error in server " . $serverName . ': ' . $e->getMessage();
     $this->getLogger()->addError($errorMessage);
     $this->getLogger()->addDebug($e);
     return $errorMessage;
 }
开发者ID:jujhars13,项目名称:gearman-ui.docker,代码行数:15,代码来源:GearmanFacade.php

示例15: __call

 /**
  * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
  * @see Engine::_CallModule
  *
  * @param $sName
  * @param $aArgs
  *
  * @return mixed
  * @throws Exception
  */
 public function __call($sName, $aArgs)
 {
     // Ввзовом метода модуля считаем, если есть подчеркивание и оно не в начале
     if (strpos($sName, '_')) {
         return E::getInstance()->_CallModule($sName, $aArgs);
     } else {
         // Если подчеркивания нет, то вызов несуществующего метода
         $oException = new Exception('Method "' . $sName . '" not exists in class "' . get_class($this) . '"');
         $aStack = $oException->getTrace();
         if (!$aStack) {
             $aStack = debug_backtrace();
         }
         // Инвертируем стек вызовов
         $aStack = array_reverse($aStack);
         // И пытаемся определить, откуда был этот некорректный вызов
         foreach ($aStack as $aCaller) {
             if (isset($aCaller['file']) && isset($aCaller['function'])) {
                 if (preg_match('/[A-Z]\\w+\\_' . preg_quote($sName) . '/', $aCaller['function']) || $aCaller['function'] == $sName) {
                     $oException->sAdditionalInfo = 'In file ' . $aCaller['file'];
                     if (isset($aCaller['line'])) {
                         $oException->sAdditionalInfo .= ' on line ' . $aCaller['line'];
                     }
                     break;
                 }
             }
         }
         throw $oException;
     }
 }
开发者ID:anp135,项目名称:altocms,代码行数:39,代码来源:LsObject.class.php


注:本文中的Exception类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。