Php – Is error suppressing bad practice

error handlingPHPprogramming practices

On a SO question I asked here about some code I was unsure about, someone replied "BTW, horrible code there: it uses the error suppressing symbol (@) a lot."

Is there a reason why this is bad practice? With things like:

$db=@new mysqli($db_info) or die('Database error');

, it allows me to display just a custom error message. Without error suppressing, then it would still display the typical PHP message of:

Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in some\file\path on line 6

as well as 'Database error'.

Is error suppressing always bad, and if so, what specifically about the above is bad?

Update: the actual code that I'm using is:

or error('Datatabase error', 'An error occurred with the database' . (($debug_mode) ? '<br />MySQL reported: <b>' . $db->error . '</b><br />Error occurred on line <b>' . __LINE__ . '</b> of <b>' . __FILE__ . '</b>' : ''))

which removes all previous output and displays an error message. So the fact that the error message doesn't include details about what specifically happened (which people seem to be suggesting as a reason why error suppressing is bad) is irrelevant.

Best Answer

I think you're doing the right thing by suppressing the error, because you are implementing your own error handling.

It might be easier to consider the equivalent in, say, Java. Suppressing the error using @ is analogous to swallowing an exception. The following code, which is similar to yours, is reasonable:

try {
    db = new MySQLi(dbInfo);
} catch (SQLException connectionFailure) {
    die("Database error");
}

(Well, in Java, you wouldn't want the servlet engine to die, but you get the idea.)

However, this isn't acceptable:

try {
    db = new MySQLi(dbInfo);
} catch (Exception e) {
}

Most PHP error suppression is done carelessly, analogous to the latter example, hence the knee-jerk reaction against your code.

Related Topic