Handling JSON data errors in Slim 3

When you send JSON data into a Slim Framework application with a content-type of application/json, then Slim will decode it for you if you use getParsedBody():

Using curl to test:

If there's an error however, you get this:

If you care about this, you can use json_last_error_msg() and return an error:

(note – in real code, you should check that the Accept header was a JSON oneā€¦)

Don't forget the JSON_PRETTY_PRINT as a human is going to be reading this error, so make it easier for them.

Use jsonlint for more information

If you really want to provide great diagnostics, then use jsonlint:

Update your handler like this:

(lint() will return NULL or a ParsingException, so we don't need to test for anything else.)

The result looks like this:

This is much more informative!

Leave a Reply

Your email address will not be published. Required fields are marked *