Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Asmir Mustafic:
How to add custom error codes to your Symfony API responses
Sep 22, 2017 @ 16:10:01

Asmir Mustafic has posted a guide on his site showing how to create custom error codes in the API responses from your Symfony-based application.

When writing APIs, a proper error handling is fundamental. HTTP status codes are a great start, but often when we deal with user inputs is not enough. If out model has complex validation rules, understanding the reason behind an 400 Bad Request error can be not trivial.

Fortunately when for symfony developers there are many libraries to deal with it. Symfony Validator, <a href="https://github.com/symfony/form>Symfony Form, <a href="https://github.com/FriendsOfSymfony/FOSRestBundle>FOS REST Bundle and JMS Serializer combined allows you to have nice error messages to be shown to your users.

He walks you through the code required to create the default error handling with an "author" example. This includes the creation of the entity as well as the form and controller to handle the request/response. He then refactors this away from the default to create the custom error handler with handlers for the message and code to be returned. The post ends with the configuration changes to register it with the application and what the result ends up looking like.

tagged: symfony tutorial custom error code api example

Link: http://www.goetas.com/blog/how-to-add-custom-error-codes-to-your-symfony-api-responses/


Trending Topics: