Does PDO errors appear inside Apache's error log?

0

Issue

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.

Solution

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.

Answered By – Your Common Sense

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More