【问题标题】:how to handle HTTPErrorException in php如何在 php 中处理 HTTPErrorException
【发布时间】:2012-04-04 15:09:14
【问题描述】:

我对一个问题感到困惑。我在函数中为未经授权的用户抛出了异常。当我调用此函数时,它显示 *Fatal error: Uncaught exception 'HTTPErrorException' * 我的代码是

throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );

我怎样才能捕捉到这个异常,以便我可以显示一些 CSS 而不是即将到来的堆栈跟踪

【问题讨论】:

    标签: php zend-framework exception exception-handling


    【解决方案1】:

    错误代码表明你没有捕获到异常,所以它会抛出这个错误。 每个异常都应该被您的代码捕获

    try {
      ....
      throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );
      ....
    } catch (HTTPErrorException $e) {
      // generate a stack trace here and show it to user
      // you can use $e->getTraceAsString() or $e->getTrace() functions here to get stack trace
    }
    

    或者如果您不想使用 try / catch 块,那么您可以创建一个异常处理函数,只要您的应用程序没有在任何地方捕获到异常,就会调用该函数

    function exception_handler($exception) {
      echo "Custom Exception: " , $exception->getMessage(), "\n";
    }
    
    set_exception_handler('exception_handler');
    

    查看有关异常的更多信息http://php.net/manual/en/language.exceptions.php

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多