Getting the exception that raised the exception "Invalid call to MyClass :: jsonSerialize ()"

In 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";
    }

Outputs: Failed calling MyClass::jsonSerialize(). How to get MyCustomExceptionthat the actual cause of this error?

+4
source share
1 answer

The answer lies in the previousclass property Exception. To get the original exception, the block try - catchshould be slightly modified:

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-selected:

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

All Articles