neomerx/json-api

Catch exceptions from json_encode

Closed this issue · 7 comments

If the json encoder in /json-api/src/Encoder/Encoder.php:413 can't parse the json properbly (e.g. Encoding problems) the function json_encode returns false. this causes in error cause of strict_types=1. This should be prevented.

Is it hypothetical or you've got some real input that can't be handled?

All our files are iso-8859-15 encoded. So I got an encoding exception when I try to use the api with strings with special chars like ü. Is there a way to set a base encoding?

@efinder2 You can set both options and depth with methods withEncodeOptions and withEncodeDepth as described here.

Thank you much. I'll try it

I'll keep it open for a while. I've got an idea of how to add some tips to use those methods or check if inputs (e.g. meta) can be encoded to JSON.

As for strings. PHP manual says All string data must be UTF-8 encoded. Have a look at predefined JSON constants that might help you.

It seems json_encode can work with any input except resources which I guess only possible if a user adds it with withMeta method. I could add catching exceptions with a message like Hey, are you sure you are not trying to encode resources? In meta section maybe? and add the caught exception which he/she gets anyway. It looks a bit gimmicky and no real value. However, if you've got a good idea of how to add it properly please don't hesitate to share it. Also, a code sample that leads to failure is welcome.

If you have any further questions please don't hesitate to ask.