Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Handing JSON Data Errors in Slim 3

DZone's Guide to

Handing JSON Data Errors in Slim 3

Rob Allen shows us how to handle JSON data errors in Slim 3.

· Web Dev Zone
Free Resource

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

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():

$app->post("/", function ($request, $response, $args) {
    $input = $request->getParsedBody();

    var_dump($input);exit;
});

Using curl to test:

$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{"foo": "bar"}'
array(1) {
  'foo' =>
  string(3) "bar"
}

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

$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{foo: bar}'
NULL

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

$app->post("/", function ($request, $response, $args) {
    $input = $request->getParsedBody();
    if ($input === null) {
        return $response->withJson(
            ['error_decoding_json' => json_last_error_msg()],
            400,
            JSON_PRETTY_PRINT
        );
    }

    var_dump($input);exit;
});

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

$ composer require seld/jsonlint

Update your handler like this:

$app->post("/", function ($request, $response, $args) {
    $input = $request->getParsedBody();
    if ($input === null) {
        $parser = new \Seld\JsonLint\JsonParser();
        $result = $parser->lint($input);
        if ($result instanceof \Seld\JsonLint\ParsingException) {
            return $response->withJson(
                ['error_decoding_json' => $result->getMessage()],
                400,
                JSON_PRETTY_PRINT
            );
        }
    }

    var_dump($input);exit;
});

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

The result looks like this:

$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{foo: bar}'
{
    "error_decoding_json": "Parse error on line 1:\n\n^\nExpected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['"
}

This is much more informative!

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.

Topics:
input ,curl ,diagnostics ,slim ,json

Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}