views:

112

answers:

7

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
be carefully about using "@" this affect the script performance. A lot
Gabriel Sosa
Hmm that's strange, never thought this would be the case. Do you know why?
Wim
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
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
+1  A: 

@ is evil.

You can use this:

try {
  // your code
} catch (Exception $e) {
  // a block that executed when the exception is raised
}
silent
That should be: } catch (Exception $e) {And it will not catch errors, only thrown exceptions.
Scott Saunders
Fixed, sorry :)
silent
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
+2  A: 

You might want to take a look at set_error_handler().

You can do anything you want registering your own handler.

Seb
+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
+1  A: 

Sounds like you are looking for a custom error handler

http://php.net/manual/en/function.set-error-handler.php

Nicky De Maeyer
+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