PHP错误处理:die()Vs trigger_error()Vs抛出异常 [英] PHP Error handling: die() Vs trigger_error() Vs throw Exception

查看:127
本文介绍了PHP错误处理:die()Vs trigger_error()Vs抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于PHP中的错误处理 - 至今我知道有3种样式:


  1. die() exit() style:

     code> $ con = mysql_connect(localhost,root,password); 

    if(!$ con){
    die('Could not connect:'。mysql_error());
    }


  2. throw Exception style:

      if(!function_exists('curl_init')){

    throw new Exception ('需要CURL PHP扩展。
    Recomplie PHP with curl');
    }


  3. trigger_error() style:

      if(!is_array($ config)&& isset($ config)){
    trigger_error('Error:config不是数组或未设置',E_USER_ERROR);
    }


现在, PHP手册全部采用三种方法。




  • 我想知道的是我应该选择哪种风格为什么?


  • 这3个是否相互替代?因此可以互换使用?




稍微OT:只是我或大家认为PHP错误处理选项只是太多在某种程度上混淆了php开发人员?

解决方案

第一个不应该用于生产代码,因为它传送与最终用户无关的信息(用户不能对无法连接到数据库进行任何操作。



如果您知道某个关键代码点,您的应用程序可能会失败,并且希望您的代码在多个通话级别恢复,您将抛出异常。



trigger_error()可让您进行细粒度错误报告(通过使用不同级别的错误消息),您可以将最终用户的错误隐藏起来(使用 set_error_handler() ),但仍然让他们在睾丸期间显示给你



另外 trigger_error()可以产生在开发期间重要的非致命消息,可以在生产代码中抑制使用自定义错误处理程序。您也可能会产生致命错误( E_USER_ERROR ),但这些错误无法恢复。如果您触发其中之一,那么程序执行停止。这就是为什么,对于致命的错误,应该使用例外。这样,您可以更好地控制程序的流程:

  //示例(数据库查询的伪代码): 

$ db-> query('START TRANSACTION');

尝试{
while($ row = gather_data()){
$ db-> query('INSERT INTO'table`(`foo`,`bar`) VALUES(?,?)',...);
}
$ db-> query('COMMIT');
} catch(Exception $ e){
$ db-> query('ROLLBACK');
}

这里,如果 gather_data()只是平淡的(使用 E_USER_ERROR die())有一个机会,以前的 INSERT 语句将会将其存入您的数据库,即使不需要,您也无法控制接下来发生的事情。


In regards to Error handling in PHP -- As far I know there are 3 styles:

  1. die()or exit() style:

    $con = mysql_connect("localhost","root","password");
    
    if (!$con) {
     die('Could not connect: ' . mysql_error());
    }
    

  2. throw Exception style:

     if (!function_exists('curl_init')) {
    
          throw new Exception('need the CURL PHP extension. 
                               Recomplie PHP with curl');
        }
    

  3. trigger_error() style:

    if(!is_array($config) && isset($config)) {
            trigger_error('Error: config is not an array or is not set', E_USER_ERROR);
        }
    

Now, in the PHP manual all three methods are used.

  • What I want to know is which style should I prefer & why?

  • Are these 3 drop in replacements of each other & therefore can be used interchangeably?

Slightly OT: Is it just me or everyone thinks PHP error handling options are just too many to the extent it confuses php developers?

解决方案

The first one should never be used in production code, since it's transporting information irrelevant to end-users (a user can't do anything about "Cannot connect to database").

You throw Exceptions if you know that at a certain critical code point, your application can fail and you want your code to recover across multiple call-levels.

trigger_error() lets you fine-grain error reporting (by using different levels of error messages) and you can hide those errors from end-users (using set_error_handler()) but still have them be displayed to you during testing.

Also trigger_error() can produce non-fatal messages important during development that can be suppressed in production code using a custom error handler. You can produce fatal errors, too (E_USER_ERROR) but those aren't recoverable. If you trigger one of those, program execution stops at that point. This is why, for fatal errors, Exceptions should be used. This way, you'll have more control over your program's flow:

// Example (pseudo-code for db queries):

$db->query('START TRANSACTION');

try {
    while ($row = gather_data()) {
       $db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...);
    }
    $db->query('COMMIT');
} catch(Exception $e) {
    $db->query('ROLLBACK');
}

Here, if gather_data() just plain croaked (using E_USER_ERROR or die()) there's a chance, previous INSERT statements would have made it into your database, even if not desired and you'd have no control over what's to happen next.

这篇关于PHP错误处理:die()Vs trigger_error()Vs抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆