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.

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站