jms/serializer with custom error codes

 

This solution contains a Symfony 5 application with jms/serializer-bundle enabled and configured to send custom error codes JSON API in case of validation errors.

The strategy for this solution has been explained in detail in this blog post.

By default symfomny error message can be displayed to users, but if the API has to be consumed by some other software (as example a mobile app), the error message are not sufficient anymore. It becomes necessary to have "error codes", and API clients can rely on those to handle errors.

Preview

Here an example on how it will look the output in case of errors triggered by symfony/form

{
    "code": 400,
    "message": "Validation Failed",
    "errors": {
        "children": {
            "name": {
                "errors": [
                    "This value should not be blank."
                ],
                "error_codes": [
                    "NOT_EMPTY"
                ]
            },
            "email": {
                "errors": [
                    "This value is not a valid email address."
                ],
                "error_codes": [
                    "INVALID_EMAIL",
                    "EMAIL_VALIDATION_FAILED"
                ]
            }
        }
    }
}

Here an example on how it look the output in case of errors triggered by symfony/validator

[
    {
        "property_path": "name",
        "message": "This value should not be blank.",
        "error_codes": [
            "NOT_EMPTY"
        ]
    },
    {
        "property_path": "email",
        "message": "This value is not a valid email address.",
        "error_codes": [
            "INVALID_EMAIL",
            "EMAIL_VALIDATION_FAILED"
        ]
    }
]

Project tree structure:

.
├── bin
│   └── console
├── config
│   ├── bootstrap.php
│   ├── bundles.php
│   ├── packages
│   │   ├── cache.yaml
│   │   ├── dev
│   │   │   └── jms_serializer.yaml
│   │   ├── fos_rest.yaml
│   │   ├── framework.yaml
│   │   ├── jms_serializer.yaml
│   │   ├── prod
│   │   │   ├── jms_serializer.yaml
│   │   │   └── routing.yaml
│   │   ├── routing.yaml
│   │   ├── sensio_framework_extra.yaml
│   │   ├── translation.yaml
│   │   ├── twig.yaml
│   │   └── validator.yaml
│   ├── routes
│   │   ├── annotations.yaml
│   │   └── dev
│   │       └── framework.yaml
│   └── services.yaml
├── public
│   └── index.php
├── src
│   ├── Controller
│   │   └── DefaultController.php
│   ├── Entity
│   │   └── Customer.php
│   ├── Form
│   │   └── CustomerType.php
│   ├── Kernel.php
│   └── Serializer
│       ├── ConstraintViolationHandler.php
│       └── FormErrorHandler.php
├── templates
│   └── base.html.twig
├── var
│   ├── cache
│   └── log
├── composer.json
├── composer.lock
├── symfony.lock
└── README.md

php, api, json, rest, serializer, xml, symfony

Want more info?