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?
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;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With