1

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.

0

7 Answers 7

3

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

You can do anything you want registering your own handler.

Sign up to request clarification or add additional context in comments.

Comments

2

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
    }

Comments

2

@ is evil.

You can use this:

try {
  // your code
} catch (Exception $e) {
  // a block that executed when the exception is raised
}

2 Comments

That should be: } catch (Exception $e) { And it will not catch errors, only thrown exceptions.
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
1

Sounds like you are looking for a custom error handler

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

Comments

1

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

0

Prefixing your function call with an @, so using @parse_url() should hide the error

3 Comments

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

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.