Development

Error Handling and the PHP @ Operator

I have been trying to debug a plugin for WordPress (Shorten2Ping – I will keep plugging this because I think it is so nifty!) and I was running into a problem where the plugin would silently fail with nothing in the logs, no error printing to screen, just dead silence.

I turned on display_errors in php.ini for a while to see if anything would show up. Still nothing. So I started to look through the file again. I knew it was getting as far as creating the short url in bit.ly before it died, but nothing was getting entered into the database. So I started through the make_bitly_url() function and what jumped out and slapped me in the face? $json = @json_decode($response,true); That little, innocuous-looking @ was gulping the error message from a fatal error! (Namely, “Call to undefined function json_decode()“). It turns out that I had PHP compiled with –disable-json, which is default for Gentoo unless you have json in your USE flags.

According to the PHP docs for the Error Control Operator @:

Currently the “@” error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use “@” to suppress errors from a certain function and either it isn’t available or has been mistyped, the script will die right there with no indication as to why.

So, if you really must supress error messages, do so, but do so with care. In the case where a suppressed error may be fatal (as in this case) be sure to add documentation to that effect. As in “If this dies a silent death it may very well be that you do not have function xyz() enabled.”

And, note to self, when debugging PHP, the first thing to do is look for and remove the error control operator.

4 comments Error Handling and the PHP @ Operator

Samuel says:

Removed @ operator for the next version ;)

I’ve found tons of issues with the @ sign when programming in PHP (see: http://www.102degrees.com/blog/2007/07/27/the-perils-of-the-at-in-php/). Congrats to Samuel for removing it :)

Ulysses says:

It’s probably not good practice to suppress errors using @ sign, then what is the preferred method.

You are generally better off either wrapping code in a try catch block and handling the error there, or if it is something that will not halt or harm the processing of the page set display_errors=0 and log_errors=1 in php.ini (at least on production sites, where that should be a standard part of your setup).

Comments are closed.