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.
7 Answers
You might want to take a look at set_error_handler().
You can do anything you want registering your own handler.
Comments
@ is evil.
You can use this:
try {
// your code
} catch (Exception $e) {
// a block that executed when the exception is raised
}
2 Comments
Scott Saunders
That should be: } catch (Exception $e) { And it will not catch errors, only thrown exceptions.
Wim
Except that non of the standard PHP function use exceptions, they only use normal errors. You can convert these into exceptions, though, see here: be.php.net/manual/en/class.errorexception.php
Sounds like you are looking for a custom error handler
Comments
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) {
Comments
Prefixing your function call with an @, so using @parse_url() should hide the error
3 Comments
Gabriel Sosa
be carefully about using "@" this affect the script performance. A lot
Wim
Hmm that's strange, never thought this would be the case. Do you know why?
Cal
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.986s bad url, no @ : 1.519s good url, with @ : 3.612s bad url, with @ : 2.567s Using 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.