【问题标题】:How to handle error or exception into php? [duplicate]如何处理php中的错误或异常? [复制]
【发布时间】:2016-01-23 04:39:38
【问题描述】:

我不知道如何处理 php 中的错误,包括运行时和编译时。我想管理所有类型的错误。

通知、警告、解析错误、致命错误

当这些类型的错误发生时,我希望我的程序在页面上抛出一个自定义的书面消息。目前我正在使用try{} catch{}set_error_handler

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

简而言之:如果我输入了错误的变量声明,例如 d 而不是 $d,或者如果我忘记了一行中的分号,或者如果我得到一个MySQL 错误。

【问题讨论】:

  • 你做过什么研究或写过什么代码?
  • @Machavity,我不同意这是重复的 - 这个问题似乎解决了错误和异常之间的差异。这个问题询问处理这两种类型的问题。我会说它相关的。

标签: php mysqli error-handling exception-handling runtime-error


【解决方案1】:

你想调试你的错误而不是抑制它们。编写代码是 25% 的编码和 75% 的调试(有争议)。您给出抑制错误的原因只是从一开始就编写了糟糕的代码。

【讨论】:

    【解决方案2】:

    您需要设置both、错误处理程序和异常处理程序。当同时抛出错误和未捕获的异常时,您将看到两条消息都显示:

    <?php
    function exception_handler($exception) {
        echo "Custom exception message: " . $exception->getMessage() . "\n";
    }
    
    function error_handler($errno, $errstr, $errfile, $errline) {
        echo "Custom error message: "  . $errstr . "\n";
    }
    
    set_exception_handler('exception_handler');
    set_error_handler('error_handler');
    
    //This exception will *not* cause exception_handler() to execute - 
    //we have addressed this exception with catch.
    try{
        throw new Exception('I will be caught!');
    } catch (Exception $e) {
        echo "Caught an exception\n";
    }
    
    //Unmanged errors
    trigger_error("I'm an error!");
    throw new Exception("I'm an uncaught exception!");
    ?>
    

    输出:

    遇到异常

    自定义错误消息:我出错了!

    自定义异常消息:我是未捕获的异常!

    您可以(并且应该)仍然使用try{} ... catch(){} 来解决出现的错误,但是在脚本完成执行后,异常处理程序将不会处理这些错误。

    更多关于exception handlers的信息。

    更多关于error handlers的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-15
      • 2011-04-03
      • 1970-01-01
      • 2017-05-29
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多