Art4/json-api-client

Parser::isValidResponseString() for errors

Closed this issue ยท 7 comments

Considering this case:

<?php
use Art4\JsonApiClient\Helper\Parser;

$errorResponseText = '{
    "errors": [
        {
            "code": 123,
            "status": 500,
            "title": "Test Error",
            "detail": "Test error detail"
        }
    ]
';

var_dump(Parser::isValidResponseString($errorResponseText));
// Current result is false but it should be true because a response document can be a document of error objects.
// Reference: https://jsonapi.org/format/#document-structure
Art4 commented

Hey ๐Ÿ‘‹ and thank you for your contribution.

The reference stated that code and status have to be expressed as a string value, see https://jsonapi.org/format/1.0/#error-objects

  • status: the HTTP status code applicable to this problem, expressed as a string value.
  • code: an application-specific error code, expressed as a string value.

Thats why Parser returns false. See also the reference examples for the right format: https://jsonapi.org/examples/#error-objects-basics

So you should fix your JSON API string and it will be valid again.

<?php
use Art4\JsonApiClient\Helper\Parser;

$errorResponseText = '{
    "errors": [
        {
-            "code": 123,
-            "status": 500,
+            "code": "123",
+            "status": "500",
            "title": "Test Error",
            "detail": "Test error detail"
        }
    ]
';

var_dump(Parser::isValidResponseString($errorResponseText));
// Now the result is true

Thank you for your quick reply, problem solved now, it's my bad for didn't noticed the value type. You made a great library, thank you again for your work.

Sorry but one quick question. Does your lib support listing all the mistakes in a document object? Like, for example, I'm looking for a function to show all the wrong points in the response string. Would be something like:

<?php
$responseString = '...';
$validation = Parser::validate($responseString);

if ($validation->fails()) {
    $errors = $validation->errors();
    /**
    * ['code should be a string', 'status should be a string']
    */
}
Art4 commented

Does your lib support listing all the mistakes in a document object?

No, not at the moment, but I have this feature in mind. Also because of that the default (and only) manager is called ErrorAbortManager, because it aborts after the first error.

I'm thinking about an ErrorCollectManager or something that could collect the errors and show them as the result. I had no time to implement this feature and a PR would be awesome. ๐Ÿ‘

I'm now preparing for a real product using JsonApi standard and I'm making a Server-side implementation lib, it's also depended on your lib so I would be happy if I could become a contributor for your lib.

Art4 commented

I'm glad to hear that. ๐Ÿ˜Š I'm looking forward to improve the library together.