Suppress error with @ operator in PHP
Asked Answered
P

19

77

In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?

If so, in what circumstances would you use this?

Code examples are welcome.

Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use

@fopen($file);

and then check afterwards... but you can get rid of the @ by doing

if (file_exists($file))
{
    fopen($file);
}
else
{
    die('File not found');
}

or similar.

I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?

Plutocracy answered 25/9, 2008 at 23:37 Comment(2)
Your example doesn't work; "File not found" is not the only way fopen() can fail. Perhaps the file isn't readable. Perhaps it's open by another process. The error conditions are platform-dependent and anyway you might not want to spend time thinking up failure cases.Outcrop
see also: stackoverflow.com/questions/1087365Irreclaimable
C
28

I would suppress the error and handle it. Otherwise you may have a TOCTOU issue (Time-of-check, time-of-use. For example a file may get deleted after file_exists returns true, but before fopen).

But I wouldn't just suppress errors to make them go away. These better be visible.

Creation answered 26/9, 2008 at 7:11 Comment(3)
The problem with that is that you end up suppressing other errors that you didn't predict and then spend your entire day trying to track down a bug that isn't throwing any errors. In the rare situation of a TOCTOU issue I think it's far better for an error to be thrown as PHP errors should not be displayed to end users anyway, but it will still allow somebody to be aware of the situation through logging of errors or displaying it if the script is running in a development environment. Error supression is the best way to hide a problem. (eg. files being deleted :) )Klan
This is fine, but for the love of not being hunted down and murdered, please check for the right error. I once spent way too long tracking down a database problem - I was seeing Close() failures, and nothing was working. Eventually I discovered that the genious @'d the initial connection, and the "else" check was essentially empty. Removing the @, I was immediately able to discern that the connection credentials were bad.Common
Very good point but how do you do that? @ doesn't let us go back and see what was suppressed as far as i know. All we need here is just handling the error and then not report it.Fullscale
K
130

Note: Firstly, I realise 99% of PHP developers use the error suppression operator (I used to be one of them), so I'm expecting any PHP dev who sees this to disagree.

In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?

Short answer:
No!

Longer more correct answer:
I don't know as I don't know everything, but so far I haven't come across a situation where it was a good solution.

Why it's bad:
In what I think is about 7 years using PHP now I've seen endless debugging agony caused by the error suppression operator and have never come across a situation where it was unavoidable.

The problem is that the piece of code you are suppressing errors for, may currently only cause the error you are seeing; however when you change the code which the suppressed line relies on, or the environment in which it runs, then there is every chance that the line will attempt to output a completely different error from the one you were trying to ignore. Then how do you track down an error that isn't outputting? Welcome to debugging hell!

It took me many years to realise how much time I was wasting every couple of months because of suppressed errors. Most often (but not exclusively) this was after installing a third party script/app/library which was error free in the developers environment, but not mine because of a php or server configuration difference or missing dependency which would have normally output an error immediately alerting to what the issue was, but not when the dev adds the magic @.

The alternatives (depending on situation and desired result):
Handle the actual error that you are aware of, so that if a piece of code is going to cause a certain error then it isn't run in that particular situation. But I think you get this part and you were just worried about end users seeing errors, which is what I will now address.

For regular errors you can set up an error handler so that they are output in the way you wish when it's you viewing the page, but hidden from end users and logged so that you know what errors your users are triggering.

For fatal errors set display_errors to off (your error handler still gets triggered) in your php.ini and enable error logging. If you have a development server as well as a live server (which I recommend) then this step isn't necessary on your development server, so you can still debug these fatal errors without having to resort to looking at the error log file. There's even a trick using the shutdown function to send a great deal of fatal errors to your error handler.

In summary:
Please avoid it. There may be a good reason for it, but I'm yet to see one, so until that day it's my opinion that the (@) Error suppression operator is evil.

You can read my comment on the Error Control Operators page in the PHP manual if you want more info.

Klan answered 6/6, 2009 at 18:47 Comment(17)
This is absolutely correct. Suppressing errors is a fundamental mistake. Use your error handler, or use exceptions, don't hide the error.Jemadar
Even "isset" is faster than "@",i still prefer using "@": <code> $_LOG_TYPES=array('request', 'click'); $t1=time().substr(microtime(),2,6); for ($i=0;$i<10000;++$i) {$log_type=in_array(@$_GET['log_type'], $_LOG_TYPES)?$_GET['log_type']:'unknown'; } $t2=time().substr(microtime(),2,6); echo 'time_length:'.((float)$t2-(float)$t1); $t1=time().substr(microtime(),2,6); for ($i=0;$i<10000;++$i) {$log_type=in_array(isset($_GET['log_type'])?$_GET['log_type']:null, $_LOG_TYPES)?$log_type:'unknown'; } $t2=time().substr(microtime(),2,6); echo 'time_length:'.((float)$t2-(float)$t1); </code>Mistook
-1 for parroting a silly "is evil" meme. Eschewing a built-in language feature with explicit disregard for the actual use case is the prime definition of cargo cult programming. -- In particular this rant fails to mention that suppressed errors are not factually gone. A custom error handler can still revive them (set_error_handler("var_dump"); is a lazy equivalent of the scream extension). Moreover such overbroad advisories lead to the commonplace isset() notice suppression syntax workarounds, which actually can obstruct debugging (as the debug notices are then suppressed irretrievably).Latashialatch
@Latashialatch "with explicit disregard for the actual use case"... hmmmm.. maybe you didn't read the full text of "is evil". "There may be a good reason for it, but I'm yet to see one, so until that day it's my opinion that the (@) Error suppression operator is evil". I was saying I was yet to find such a context. It seems like you have an answer for the question the Op asked, perhaps you might consider submitting one where there would be more room to discuss your views.Klan
I disagree. @ is fine for handling forms. For example, you may wish to suppress notices as short-hand using user-submitted variables, like: if (@$_POST['test'])... PHP notices that are set to be shown can throw off things like JSON response bodies and HTML design. This is still an 'error', but it's not an "evil" error or a problem with your code.Eisenstark
Your code doesn't check the index exists before checking it's value. This will lead to hard to track down issues, say if a form element is renamed or mistyped. A non existent index means something different to a form element left blank. Also you shouldn't be displaying errors to end users. If you are just having HTML/JSON problems in development and think it's fine to leave them, this is where we disagree. Notices on a typical execution path generally indicate a failure to handle conditions you should be handling.Klan
I totally agree with you, however I think I have found one situation when @ seems to be the best solution. It is with stat() - take a look here and check my answer and tell me if you disagree with me that it cannot be avoided.Roach
I disagree that there is no acceptable usage case. sometimes, you need need to assign a value of a superglobal to a variable, with get being the primary place this problem will arise. obviously, you can't say $_GET = null,because it may contain other variables you need.isset is impractical for multiple gets in a single view. solution? a one line wonder for each of your maybe present variables: @$foo = $_GET['foo'] or NULL; then, you have logic to check whether each variable is empty with empty(). best solution for this use case requires @ to suppress the meaningless warning.Histo
@Zaffy The problem appears to be that file_exists wasn't working for a particular case, but I think that Mark Wu pointed out the reason and the fix. @Histo It was hard to follow, but are you saying that you want to do: @$foo = $_GET['foo'] or NULL; instead of $foo = isset($_GET['foo']) ? $_GET['foo'] : NULL;?Klan
Using empty($var) when the variable definitely exists is silly, just use !$var when you know it exists. empty($var)===(!isset($var)||!$var). If you want to avoid undefined errors when pulling values from an array, try this $_GET+=['key1'=>'','key2'=>'','key3'=>'']; this way, any parameters that weren't passed will be filled in with whatever value you provide.Elfie
If you want to check for the existence of multiple keys, then instead of if (!isset($_GET['key1'],$_GET['key2'],$_GET['key3'])) {/*error*/}, you could use if (array_diff_key(array_flip(['key1','key2','key3'),$_GET)) {/*error*/}. What happens is the first array gets turned into ['key1'=>0,'key2'=>1,'key3'=>2] and then any keys that are also in $_GET are removed, if array_diff_key() returns an empty array (which is treated as false), you're good to go. If the array name length is short and you don't need to check many keys, isset() is shorter, but can be much longer otherwise.Elfie
@Gerry: You were right. Hope that helps others: had an @ on an include statement and when the app would crash at times, nothing would get logged in php error log. Reason is there was an @ on an include spans MUCH more than the if it was included successfully or not, only but also applies to functions coming from a suppressed "include", they will NOT log errors when you call them later on. No more @ on includes for me.Narghile
I will give you a good reason. If you have to delete a group of files with glob and unlink and you don't care if files actually exist on disk and you don't want to have your logs filled with No such file or directory, then @ is what you need.Absent
@ViktorJoras do an exists check before unlink. There may be 0.001% of time where a file is deleted between these two checks and you end up with a single log entry. This is far better than the situation you will run into where you accidentally suppress an error you want to know about but never predicted would happen when you added @.Klan
@Klan there are situations where you don't really care about the function's overcome and you don't want to know if function is failing for no reason in the world. @ is meant for these very situations.Absent
@ is something that wouldn't be used until needed. Example, when there are no other ways to avoid a warning that you don't care, other than suppressing it: echo @convert_uudecode('hello');Parthena
-1 Supressing errors is bad but the correct way to handle errors from fopen() is similar to low level C programming: you execute the syscall and inspect the return value. Just because file_exists() succeeded a few ms earlier doesn't mean that the fopen() is going to succeed now. The only way to avoid race condition is to check the return value of fopen() and to avoid log spam you have to use @ for this special case. You can read @ here as "I promise to check the return value by myself" instead of "suppress errors". For functions that are not syscalls, things are different.Colloquy
C
28

I would suppress the error and handle it. Otherwise you may have a TOCTOU issue (Time-of-check, time-of-use. For example a file may get deleted after file_exists returns true, but before fopen).

But I wouldn't just suppress errors to make them go away. These better be visible.

Creation answered 26/9, 2008 at 7:11 Comment(3)
The problem with that is that you end up suppressing other errors that you didn't predict and then spend your entire day trying to track down a bug that isn't throwing any errors. In the rare situation of a TOCTOU issue I think it's far better for an error to be thrown as PHP errors should not be displayed to end users anyway, but it will still allow somebody to be aware of the situation through logging of errors or displaying it if the script is running in a development environment. Error supression is the best way to hide a problem. (eg. files being deleted :) )Klan
This is fine, but for the love of not being hunted down and murdered, please check for the right error. I once spent way too long tracking down a database problem - I was seeing Close() failures, and nothing was working. Eventually I discovered that the genious @'d the initial connection, and the "else" check was essentially empty. Removing the @, I was immediately able to discern that the connection credentials were bad.Common
Very good point but how do you do that? @ doesn't let us go back and see what was suppressed as far as i know. All we need here is just handling the error and then not report it.Fullscale
O
24

Yes suppression makes sense.

For example, the fopen() command returns FALSE if the file cannot be opened. That's fine, but it also produces a PHP warning message. Often you don't want the warning -- you'll check for FALSE yourself.

In fact the PHP manual specifically suggests using @ in this case!

Outcrop answered 25/9, 2008 at 23:39 Comment(8)
but, surely, this can be avoided by checking file_exists($file) first?Plutocracy
No it can't, there are other failure conditions such as "no permissions to read" or "file busy."Outcrop
That's great until fopen throws an error you weren't anticipating. You can't check for all of your known error conditions? Create an fopen wrapper function.Klan
I was tempted to plus you 1 just because you are Jason Cohen. Great answer/comment.Messier
@JasonCohen What about secure.php.net/is_readable? There is still a race condition however...Socialite
If you have to worry about race conditions, you may have bigger problems to worry about (though I'm thinking of things like including dynamically generated/deleted php files, which is a terrible idea).Elfie
@Klan If fopen throws an error (fatal error, generating an exception), it will be reported (displayed at screen, logged in php_error.log) regardless you use @ or not. @ operator doesnt hide (or "suppress") errors since PHP 7, only suppress warnings and notice. I guess you think that @ supress all kind of errors (PHP 5)... it has changed now... so following Jason idea, I would code the following: try { @fopen($file); ... } catch (Throwable $e){ ..//only fatal error throw exceptions } as warning and notice are not caught or controlled by try/ catch block.Phanerogam
+1 Similar to C programming, a well made program will execute the required syscall and then inspect the return value. If you separate fopen() from file_exists() you just created possibility for a race condition. Imagine two PHP processes each running file_exists(), getting false in parallel and then both processes proceed to create a new file with fopen(). PHP has stupid default behavior of emitting a warning which goes contrary the best possible implementation so @ is totally okay here as long as you inspect the return value of fopen().Colloquy
S
13

If you don't want a warning thrown when using functions like fopen(), you can suppress the error but use exceptions:

try {
    if (($fp = @fopen($filename, "r")) == false) {
        throw new Exception;
    } else {
        do_file_stuff();
    }
} catch (Exception $e) {
    handle_exception();
}
Synod answered 26/9, 2008 at 4:7 Comment(1)
If you are throwing an exception then you don't strictly need the else, just do_file_stuff().Precast
T
7

Error suppression should be avoided unless you know you can handle all the conditions.

This may be much harder than it looks at first.

What you really should do is rely on php's "error_log" to be your reporting method, as you cannot rely on users viewing pages to report errors. ( And you should also disable php from displaying these errors )

Then at least you'll have a comprehensive report of all things going wrong in the system.

If you really must handle the errors, you can create a custom error handler

http://php.net/set-error-handler

Then you could possibly send exceptions ( which can be handled ) and do anything needed to report weird errors to administration.

Tarnation answered 25/9, 2008 at 23:51 Comment(3)
I know I shouldn't supress the errors, but some things will throw an E_WARNING or an E_NOTICE, when it's not needed to actually show that to the end user, and in a lot of cases, it can be avoided to actually theow these. except, for now in the case of mysql_openPlutocracy
@martin meredith: thats why you use "error_log" and "display_errors=false"Tarnation
@Kent - Best answer on this page by far! [edit: make that second best, because I just added one :P] @Plutocracy - As Kent has suggested, set up an error handler that only displays errors to you.Klan
B
7

I NEVER allow myself to use '@'... period.

When I discover usage of '@' in code, I add comments to make it glaringly apparent, both at the point of usage, and in the docblock around the function where it is used. I too have been bitten by "chasing a ghost" debugging due to this kind of error suppression, and I hope to make it easier on the next person by highlighting its usage when I find it.

In cases where I'm wanting my own code to throw an Exception if a native PHP function encounters an error, and '@' seems to be the easy way to go, I instead choose to do something else that gets the same result but is (again) glaringly apparent in the code:

$orig = error_reporting(); // capture original error level
error_reporting(0);        // suppress all errors
$result = native_func();   // native_func() is expected to return FALSE when it errors
error_reporting($orig);    // restore error reporting to its original level
if (false === $result) { throw new Exception('native_func() failed'); }

That's a lot more code that just writing:

$result = @native_func();

but I prefer to make my suppression need VERY OBVIOUS, for the sake of the poor debugging soul that follows me.

Berti answered 15/7, 2009 at 20:51 Comment(3)
This is an opinion and not a very good one. You can accomplish the same thing with $result = @native_func(); and if($result) w/o that ugly ass mess. I agree @ is bad, but only if its not handled.Hoop
Do you think, it is more kosher than @fopen? You also disables the error reporting but with more code and greater execution time. IIRC try...catch will not work due to it is warning not error... try...catch will be one kosher solution in this case. It is hiding NetBeans warning only...Leisaleiser
The problem I'm trying to solve here is highlighting to the next developer that suppression is being done. I choose to sacrifice lines of code, micro-optimized execution time, and presumed ugliness in order to achieve my goal. I don't see a "one best way" that covers all needs, so this is how I choose my trade-offs.Berti
S
5

Most people do not understand the meaning of error message.
No kidding. Most of them.

They think that error messages are all the same, says "Something goes wrong!"
They don't bother to read it.
While it's most important part of error message - not just the fact it has been raised, but it's meaning. It can tell you what is going wrong. Error messages are for help, not for bothering you with "how to hide it?" problem. That's one of the biggest misunderstandings in the newbie web-programming world.

Thus, instead of gagging error message, one should read what it says. It has not only one "file not found" value. There can be thousands different errors: permission denied, save mode restriction, open_basedir restriction etc.etc. Each one require appropriate action. But if you gag it you'll never know what happened!

The OP is messing up error reporting with error handling, while it's very big difference!
Error handling is for user. "something happened" is enough here.
While error reporting is for programmer, who desperately need to know what certainly happened.

Thus, never gag errors messages. Both log it for the programmer, and handle it for the user.

Swage answered 6/10, 2010 at 8:12 Comment(0)
S
3

is there not a way to suppress from the php.ini warnings and errors? in that case you can debug only changing a flag and not trying to discovering which @ is hiding the problem.

Sampler answered 25/9, 2008 at 23:45 Comment(1)
yes, you can do error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING) - but I don't want to do this, see edited questionPlutocracy
S
3

Using @ is sometimes counter productive. In my experience, you should always turn error reporting off in the php.ini or call

error_reporting(0);

on a production site. This way when you are in development you can just comment out the line and keep errors visible for debugging.

Sabadilla answered 26/9, 2008 at 0:3 Comment(3)
I prefer for errors to be visible. What I'm trying to work out, if is there is any way that you would have to use an @ or you might have an error, that cannot be caught before.Plutocracy
I've never seen an instance where using @ for error suppression was a positive thing. It hides all future errors, not just the one that you wanted to ignore.Klan
Don't turn error_reporting off, that's madness! While you're turning it back on, make sure it's able to log errors to a file that you can read later. The proper way to not show errors to users is via ini_set('display_errors',0); or better yet, directly modify the ini file to include that.Elfie
D
3

One place I use it is in socket code, for example, if you have a timeout set you'll get a warning on this if you don't include @, even though it's valid to not get a packet.

$data_len = @socket_recvfrom( $sock, $buffer, 512, 0, $remote_host, $remote_port )
Deadfall answered 26/9, 2008 at 1:22 Comment(0)
M
3

The only place where I really needed to use it is the eval function. The problem with eval is that, when string cannot be parsed due to syntax error, eval does not return false, but rather throws an error, just like having a parse error in the regular script. In order to check whether the script stored in the string is parseable you can use something like:

$script_ok = @eval('return true; '.$script);

AFAIK, this is the most elegant way to do this.

Meagher answered 21/7, 2009 at 0:12 Comment(1)
First off, eval() shouldn't ever be used. Second, if $script contains functions, they will be evaluated and then the second time this is run, it will complain that those functions were already defined and terminate.Elfie
F
3

Today I encountered an issue that was a good example on when one might want to use at least temporarily the @ operator.

Long story made short, I found logon info (username and password in plain text) written into the error log trace.

Here a bit more info about this issue.

The logon logic is in a class of it's own, because the system is supposed to offer different logon mechanisms. Due to server migration issues there was an error occurring. That error dumped the entire trace into the error log, including password info! One method expected the username and password as parameters, hence trace wrote everything faithfully into the error log.

The long term fix here is to refactor said class, instead of using username and password as 2 parameters, for example using a single array parameter containing those 2 values (trace will write out Array for the paramater in such cases). There are also other ways of tackling this issue, but that is an entire different issue.

Anyways. Trace messages are helpful, but in this case were outright harmful.

The lesson I learned, as soon as I noticed that trace output: Sometimes suppressing an error message for the time being is an useful stop gap measure to avoid further harm.

In my opinion I didn't think it is a case of bad class design. The error itself was triggered by an PDOException ( timestamp issue moving from MySQL 5.6 to 5.7 ) that just dumped by PHP default everything into the error log.

In general I do not use the @ operator for all the reasons explained in other comments, but in this case the error log convinced me to do something quick until the problem was properly fixed.

Foulk answered 13/2, 2019 at 6:25 Comment(2)
Follow up on my post above. These days it's not required to use the @ at all, even in my case state above. The proper way to handle is to remove it from being handled in stack reports, etc. Here's how this could look function login ( #[SensitiveParameter] string password);Foulk
Couldn't edit anymore. Sorry. See php.net/manual/en/class.sensitiveparameter.phpFoulk
R
3

Some functions in PHP will issue an E_NOTICE (the unserialize function for example).

A possible way to catch that error (for PHP versions 7+) is to convert all issued errors into exceptions and not let it issue an E_NOTICE. We could change the exception error handler as follow:

function exception_error_handler($severity, $message, $file, $line) {                                                                       
    throw new ErrorException($message, 0, $severity, $file, $line);          
}                                                                            

set_error_handler('exception_error_handler');                          

try {             
    unserialize('foo');
} catch(\Exception $e) {
    // ... will throw the exception here
}       
Roundtheclock answered 27/3, 2020 at 13:4 Comment(0)
P
1

You do not want to suppress everything, since it slows down your script.

And yes there is a way both in php.ini and within your script to remove errors (but only do this when you are in a live environment and log your errors from php)

<?php
    error_reporting(0);
?>

And you can read this for the php.ini version of turning it off.

Podgorica answered 25/9, 2008 at 23:48 Comment(3)
I'm not looking for a way to turn it off, I'm looking for whether there's a reason to use it, as in anything that cannot be handled without using @ (one item so far - mysql_connect)Plutocracy
@Industrial it is doing extra work suppressing the errors. Since it is supposed to display an error but finds an @ there and has do deal with it dynamically.Indopacific
Ah! So it would then be better to follow your example - error_reporting(0);?Grannias
A
1

I have what I think is a valid use-case for error suppression using @.

I have two systems, one running PHP 5.6.something and another running PHP 7.3.something. I want a script which will run properly on both of them, but some stuff didn't exist back in PHP 5.6, so I'm using polyfills like random_compat.

It's always best to use the built-in functions, so I have code that looks like this:

if(function_exists("random_bytes")) {
    $bytes = random_bytes(32);
} else {
    @include "random_compat/random.php"; // Suppress warnings+errors
    if(function_exists("random_bytes")) {
        $bytes = random_bytes(32);
    } else if(function_exists('openssl_random_pseudo_bytes')) {
        $bytes = openssl_random_pseudo_bytes(4);
    } else {
        // Boooo! We have to generate crappy randomness
        $bytes = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',64)),0,32);
    }
}

The fallback to the polyfill should never generate any errors or warnings. I'm checking to see that the function exists after attempting to load the polyfill which is all that is necessary. There is even a fallback to the fallback. And a fallback to the fallback to the fallback.

There is no way to avoid a potential error with include (e.g. using file_exists) so the only way to do it is to suppress warnings and check to see if it worked. At least, in this case.

Alisha answered 14/5, 2021 at 21:17 Comment(0)
I
1

I can think of one case of use, for auto-increment a non existing array key.

<?php
$totalCars = [];

// suppressing error to avoid a getting a warning error
@$totalCars['toyota']++; 
var_export($totalCars);
// array (
//   'toyota' => 1,
// )

// not suppressing error will throw a warning 
// but still allows to increase the non-existing key value 
$totalCars['ford']++;
var_export($totalCars);
// Warning: Undefined array key "ford"
// array (
//  'toyota' => 1,
//  'ford' => 1,
// )

See this example output here: https://onlinephp.io/c/433f0

Ingate answered 5/7, 2021 at 22:57 Comment(2)
This answer makes me wonder why any developer would allow themselves to let bad coding practices to persist in their code at all. Adding the @ silencer is an admission of being a dev who is comfortable with knowingly writing bad code.Reld
I am coding for 30+ years and think that it is completely valid and saves a lot of code in some instances to use the default initializer and suppress the NOTICE (this is no error!), especially when using multi-dimensional arrays which need to be initialized to 0 otherwise.Fourthly
B
0

If you are using a custom error handling function and wanna suppress an error (probably a known error), use this method. The use of '@' is not a good idea in this context as it will not suppress error if error handler is set.

Write 3 functions and call like this.

# supress error for this statement
supress_error_start();  
$mail_sent = mail($EmailTo, $Subject, $message,$headers);
supress_error_end(); #Don't forgot to call this to restore error.  

function supress_error_start(){
    set_error_handler('nothing');
    error_reporting(0);
}

function supress_error_end(){
    set_error_handler('my_err_handler');
    error_reporting('Set this to a value of your choice');
}

function nothing(){ #Empty function
}

function my_err_handler('arguments will come here'){
      //Your own error handling routines will come here
}
Boise answered 25/9, 2008 at 23:37 Comment(0)
W
0

In my experience I would say generally speaking, error suppress is just another bad practice for future developers and should be avoided as much as possible as it hides complication of error and prevent error logging unlike Exception which can help developers with error snapshot. But answering the original question which say "If so, in what circumstances would you use this?".

I would say one should use it against some legacy codes or library that don't throw exception errors but instead handles bad errors by keep the error variables with it's object(speaking of OOP) or using a global variable for logging error or just printing error all together.

Take for example the mysqli object

new mysqli($this->host, $this->username, $this->password, $this->db);

This code above barely or never throw an exception on failed connection, it only store error in mysqli::errno and mysli::error

For modern day coding the one solution I found was to suppress the ugly error messages (which helps no one especially when on production server where debug mode is off) and instead devs should throw their own exception. Which is consider modern practice and help coders track errors more quickly.

  $this->connection = @new mysqli($this->host, $this->username, $this->password, $this->db);
  if($this->connection->connect_errno)
      throw new mysqli_sql_exception($this->connection->error);

You can notice the use of suppression @ symbol to prevent the ugly error display should incase error display was turned on development server.

Also I had to throw my own exception. This way I was able to use @ symbol and same time I didn't hide error nor did I just make my own guess of what the error could be.

I will say if used rightly, then it is justifiable.

Wye answered 2/12, 2021 at 9:55 Comment(0)
U
-1

I use it when trying to load an HTML file for processing as a DOMDocument object. If there are any problems in the HTML... and what website doesn't have at least one... DOMDocument->loadHTMLFile() will throw an error if you don't suppress it with @. This is the only way (perhaps there are better ones) I've ever been successful in creating HTML scrapers in PHP.

Ulmer answered 25/9, 2008 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.