Ilija Ilija - 7 months ago 155
PHP Question

Getting an exception that triggered "Failed calling MyClass::jsonSerialize()" exception

This example:

<?php

class MyCustomException extends Exception {

}

class MyClass implements JsonSerializable {

function jsonSerialize()
{
throw new MyCustomException('For some reason, something fails here');
}

}

try {
json_encode(new MyClass);
} catch(Exception $e) {
print $e->getMessage() . "\n";
}


Will output:
Failed calling MyClass::jsonSerialize()
. How to get
MyCustomException
, that's the actual cause of this error?

Answer

The answer is in previous property of the Exception class. To get the original exception, try - catch block should be altered a bit:

try {
    json_encode(new MyClass);
} catch (Exception $e) {
    if ($e->getPrevious()) {
        print $e->getPrevious()->getMessage() . "\n";
    } else {
        print $e->getMessage() . "\n";
    }
}

This exception can also be re-thrown:

try {
    json_encode(new MyClass);
} catch (Exception $e) {
    if ($e->getPrevious()) {
        throw $e->getPrevious();
    } else {
        throw $e;
    }
}
Comments