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!

Victor Czechov
  • 237
  • 1
  • 6
  • 12

3 Answers3

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!';
}
Community
  • 1
  • 1
ruX
  • 7,224
  • 3
  • 39
  • 33
  • 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. – Victor Czechov Aug 25 '12 at 07:26
  • 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). – Victor Czechov Aug 25 '12 at 07:38
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');
Needhi Agrawal
  • 1,326
  • 8
  • 14
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.

Chris Trahey
  • 18,202
  • 1
  • 42
  • 55