I use FOERestBundle and class View. And when I validate entity I have object error like this and this is:
[
{
"property_path": "main_skill",
"message": "This value should not be blank."
},
{
"property_path": "type",
"message": "This value should not be blank."
},
{
"property_path": "description",
"message": "This value should not be blank."
}
]
I need return object error when user not valid security token like this
[
{
"property_path": "main_skill",
"message": "This value should not be blank."
},
]
now I have plain text. This my end point
/**
* Update existing Bit from the submitted data.
*
* @ApiDoc(
* resource = true,
* description = "Update single Bit",
* parameters={
* {"name"="status", "dataType"="string", "required"=false, "description"="status for bit"},
* {"name"="text", "dataType"="string", "required"=true, "description"="text for rejected"},
* {"name"="token", "dataType"="string", "required"=true, "description"="is equally md5('email'.secret_word)"}
* },
* statusCodes = {
* 200 = "Bit successful update",
* 400 = "Secret token is not valid"
* },
* section="Bit"
* )
* @RestView()
*
* @param Request $request
* @param string $id
*
* @return View
*/
public function putBitAction(Request $request, $id)
{
$manager = $this->getDoctrine()->getManager();
$token = $this->get('request')->request->get('token');
$user = $this->getDoctrine()->getRepository('MyBundle:Users')->findOneBySecuritytoken($token);
$bit = $manager->getRepository('MyBundle:Bit')->find($id);
$view = View::create();
if (!empty($user) && !empty($bit) && !empty($token)) {
*some logic
$view = $this->view($bit, 200);
return $this->handleView($view);
}
} else {
$view = $this->view('Secret token is not valid', 400);
return $this->handleView($view);
}
}
now I have plain text
Response Body [Raw]
"Secret token is not valid"
this is return object error validate and this is ok
[
{
"property_path": "main_skill",
"message": "This value should not be blank."
},
{
"property_path": "type",
"message": "This value should not be blank."
},
{
"property_path": "description",
"message": "This value should not be blank."
}
]
How to return custom error like object not plain text?
Just pass your data like an array and tell the view to render it as json should generate an output like you wanted to
$view = $this->view(
array(
'property_path' => 'main_skill',
'message' => "error"
//whatever your object/array structure is
),
500 //error code for the error
);
$view->setFormat('json');
return $this->handleView($view);