Reputation: 370
I am developing a simple Rest API (JSON only) with symfony3. I am using Forms to validate the entities but I can't figure out a good enough way to handle form errors and return a meaningful json error response. Here is an example action from my controller:
/**
* @Route("/user/add" , name="addUser")
* @Method({"POST"})
*
* @param Request $request
* @return JsonResponse
*/
public function registerAction(Request $request) {
$user = new User();
$form = $this->createForm(UserType::class, $user, ['validation_groups' => ['registration']] );
$form->handleRequest($request);
if(!$form->isValid()){
//TODO: Handle errors properly
}
$this->get('user_service')->addUser($user);
$userModel = new UserModel($user);
return new JsonResponse($userModel);
}
I am thinking about throwing a custom exception which contains the form data/errors and than handling the exception into a custom Exception Listener, parsing the form and returning a JsonResponse. But I am not sure if this is the correct way to handle form errors. I have read a lot of articles about the proper way to create a REST API and handle errors with symfony. Many of the articles were using FOSRestBundle but I couldn't get the point of using this bundle in a simple JSON only API.
Can somebody give me some suggestions how to properly handle errors into a symfony3 REST API? And also is there a good reason to use the FOSRestBundle in your opinion in the current example?
Thank you!
Upvotes: 3
Views: 1385
Reputation: 4012
If your form is not valid, you can retrieve errors like that:
$errors = [];
foreach ($form->getErrors(true) as $error) {
if ($error->getOrigin()) {
$errors[$error->getOrigin()->getName()][] = $error->getMessage();
}
}
You will get an array populated with fields which have one or several errors:
[
'field_name' => [
'text of error 1',
'text of error 2',
],
'other_field_name' => [
'text of error 1',
],
]
Then return these data in your JSON response, and on the client side you can deal with these errors. Since you have the field name, you can display them near the proper form field.
Upvotes: 9