1

I have some script, that calls an error: Fatal error: Call to a member function GetData() on a non-object in .... I'm trying to catch this error, but it doesn't work, watch my code below:

try {

    if ($data = $m->users()->GetData()) {

    print_r( $data );

}

}
catch (Exception $e) {

    echo 'Hey, it is an error man!';

}

How to catch it? Turning off all errors in php is impossible. I mean that sometimes I really need this error.

upd 1. Well, solution is simple:

if (is_object($m->users()) && ($data = $m->users()->GetData())) {
    print_r( $data );
} else {
echo 'Hey, it is an error man!';

Thank you all!

2
  • first of all, echo 'Hey, it's an error man!'; should be echo "Hey, it's an error man!"; Commented Aug 25, 2012 at 7:21
  • sorry, I was typing it, not copy-past. Commented Aug 25, 2012 at 7:28

3 Answers 3

1

In PHP errors and exceptions are from different separated worlds. Look more PHP: exceptions vs errors?

You can check returned object before call method GetData()

try {
    if (is_object($m->users()) && ($data = $m->users()->GetData())) {
        print_r( $data );
    }
} catch (Exception $e) {
    echo 'Hey, it's an error man!';
}
Sign up to request clarification or add additional context in comments.

2 Comments

really, it's my fault, damn, can I avoid this message anyhow, except usage configuration of php? I'm trying if/else, but it's ... the same t-r-o-u-b-l-e.
yes, it was helpful, but strange a one moment still, if it's not an object it's echoes nothing (would be glad if it does).
1

use following to avoid your error and you should used shutdown error handler.

try {

    $obj =  $m->users();
    if ($data =$obj->GetData()) {

    print_r( $data );

}

}
catch (Exception $e) {

    echo 'Hey, it's an error man!';

}

//shut down error handler

function shutdownErrorHandler() {
    $error = error_get_last();
    if ($error !== NULL) {
      echo "Error: [SHUTDOWN] error type: " . $error['type'] . " | error file: " . $error['file'] . " | line: " . $error['line'] . " | error message: " . $error['message'] . PHP_EOL;
    } else {
       echo "Normal shutdown or user aborted";
    }
}

register_shutdown_function('shutdownErrorHandler');

Comments

0

Fatal Errors are not the same as Exceptions, and they are not usually recoverable. What they are, however, is usually avoidable, and sometimes they are "catchable" via PHP5's set_error_handler function.

Best practice, however, is to simply do the work of checking for valid objects before trying to call methods on them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.