dongyi5070 2013-06-28 00:10
浏览 48
已采纳

PDO错误是否出现在Apache的错误日志中?

I'm learning PHP and have a question.

If I use the following code to connect to a database, will possible errors appear inside Apache's error log?

    $con = new PDO('mysql:host='.$h.';dbname='.$dbn.';charset=utf8', $u, $p);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
    $con->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);

If they do appear there, what's the reason to use try and catches?

Thanks.

  • 写回答

1条回答 默认 最新

  • dongsao8279 2013-06-28 04:33
    关注

    That's excellent question.
    Most PHP users do not understand exceptions and thinks that these has something to do with error reporting and totally misuse them! Though the right answer is rather simple:

    will possible errors appear inside Apache's error log?

    Yes, if you tell PHP to log your errors. log_errors ini setting is responsible for this.

    If they do appear there, what's the reason to use try and catches?

    That's most interesting question.
    To handle an error message one should never ever use try catches.
    This mechanism is to handle errors. Not error messages. There's essential difference, yet misunderstood by wast majority of PHP folks.

    To handle an error message all you need is to tell PHP to log errors.
    While if you are going to handle an error itself, try catches are indispensable.

    What is handling errors?
    Anything that you have to do in case of error beside error logging:

    to rollback a transaction

    try {
        $dbh->beginTransaction();
        // some SQL stuff
    } catch (Exception $e) {
        $dbh->rollback();
        throw $e;
    }
    

    note that we are rethrowing an exception after handling the error

    to make an error in the unimportant block of code non fatal

    try {
        some_non_critical_function();
    } catch (Exception $e) {
        log_error($e->getMessage().$e->getTrace());
    }
    

    here we have to log an error message manually, yet let the rest of the code run.

    and so on.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器