dqudtskm49788 2013-06-11 05:00
浏览 111
已采纳

PHP - 生产环境的合理/优雅/优雅错误处理

I'm writing a PHP web application which will be running under a production environment in the not too distant future, and rather than use the non-user-friendly die(), I thought I'd come up with a Class that handles ErrorMessages.

Basically, my thought process is this:

  1. If the web application is in debug/development mode, die() is OK.

  2. If the web application is in production/live mode, don't disturb the user with the error message - instead continue as best as possible but send an e-mail to the admin, dumping the error message and anything else we can (e.g: logged in user, session details, IP address, time, etc.)

My (rough) code is as follows:

<?php
require_once('config.php');

class ErrorMessage
{
      private $myErrorDescription;

      public function __construct($myErrorDescription)
      {
           $this->myErrorDescription = (string) $myErrorDescription;

           if (DEBUG_MODE === true)
                die($myErrorDescription);
           else
                $this->sendEmailToAdministrator();
      }

      private function sendEmailToAdministrator()
      {
        // Send an e-mail to ERROR_LOGGING_EMAIL_ADDRESS with the description of the problem.
      }
} 

?>

This Class would be used as:

if (EXPECTED_OUTCOME) {
 // ...
}
else {
    new ErrorMessage('Application failed to do XYZ');
}

Is this a sensible approach or am I reinventing the wheel here? I know that frameworks often have solutions for Error Handling, but I'm not using one (and don't really want to).

That said, should I be using Exceptions and Throw for this instead? What are the pros/cons of this approach?

  • 写回答

1条回答 默认 最新

  • douluan1533 2013-06-11 05:34
    关注

    I would suggest using Exceptions.

    You can switch php over to sending Exceptions instead of errors by doing this: (from PHP ErrorException Page)

    <?php
    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
    set_error_handler("exception_error_handler");
    
    /* Trigger exception */
    strpos();
    ?>
    

    Then in your code when you encounter an error condition throw an Exception

    throw(new Exception("Meaningful Description", "optional error number"));
    

    Exceptions can be typed so you can derive an instance so that you can target it in a catch

    class MyRecoverableException extends Exception {}
    

    Then in your code you can enclose code that may throw a potentially recoverable error in a try/catch block.

     try {
         $res = doSomething();
         if (!$res) throw new MyRecoverableException("Do Somthing Failed");
     } catch(MyRecoverableException $e){
         logError($e);
         showErrorMessage($e->getMessage());
     }
    

    This is especially useful in Database Transactions

     try {
          $db->beginTransaction();
          // do a lot of selectes and inserts and stuff
          $db->commit();
     } catch (DBException $e){
          $db->rollback();
          logError($e);
          showErrorMessage("I was unable to do the stuff you asked me too");
     }
    

    with error reporting turned on, an uncaught exception will give you a detailed stack trace that tells you where the exception was thrown.

    with error reporting turned off you will get a 500 Error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R