How to disable errors just for particular php function, and in the same time to know that the error occurred? For instance, I use a php function parse_url, to parse an array of urls, sometimes it returns an error, what I want to do is to parse next url once error occurs, and not to show it(error) on the screen.
A:
Prefixing your function call with an @
, so using @parse_url()
should hide the error
Wim
2009-11-05 16:17:10
be carefully about using "@" this affect the script performance. A lot
Gabriel Sosa
2009-11-05 16:21:22
Hmm that's strange, never thought this would be the case. Do you know why?
Wim
2009-11-05 16:25:43
That sounded suspicious, so I ran a benchmark calling parse_url() a million times for good and bad URLs, with and without the @. The results:good url, no @ : 1.986sbad url, no @ : 1.519sgood url, with @ : 3.612sbad url, with @ : 2.567sUsing PHP 5.2.5 on an unloaded machine. So you can see it's slower with the '@', but we're talking 1-2 microseconds difference per call.
Cal
2009-11-05 22:04:04
A:
To silent errors for a particular statement, simply add a @
.
Example
$file = @file_get_contents($url);
When file_get_contents
can throw error when $url is not found.
You can use the @ sign anywhere to silent any statements. Like:
$i = @(5/0);
thephpdeveloper
2009-11-05 16:17:18
+1
A:
@ is evil.
You can use this:
try {
// your code
} catch (Exception $e) {
// a block that executed when the exception is raised
}
silent
2009-11-05 16:17:33
That should be: } catch (Exception $e) {And it will not catch errors, only thrown exceptions.
Scott Saunders
2009-11-05 16:20:53
Except that non of the standard PHP function use exceptions, they only use normal errors. You can convert these into exceptions, though, see here: http://be.php.net/manual/en/class.errorexception.php
Wim
2009-11-05 16:22:54
+2
A:
You might want to take a look at set_error_handler()
.
You can do anything you want registering your own handler.
Seb
2009-11-05 16:18:04
+2
A:
the @ symbol before a function will suppress the error message and parse_url() returns false on erroring so just catch that.
if(@parse_url($url) === false) {
//Error has been caught here
}
RMcLeod
2009-11-05 16:18:22
+1
A:
the best way is to convert php "errors" to exceptions, using the technique outlined here http://php.net/manual/en/class.errorexception.php and then handle an Exception like you do in other languages:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
parse_url(...)
} catch(Exception $e) {
stereofrog
2009-11-05 16:19:18