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!