Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
Ilija Avatar asked Jan 11 '23 02:01

Ilija


1 Answers

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;
    }
}
like image 62
Ilija Avatar answered Jan 19 '23 10:01

Ilija