[英]How to set proper JSON response for POST method in RESTful API from FOSRestBundle?
我正在为RESTful API创建POST
方法。 您可能会注意到,该API是建立在FOSRestBundle和NelmioApiDoc之上的。 当文件未上传或缺少rid
参数以及使用正确的JSON响应时,我无法验证。 这就是我在做什么:
/**
* Set and upload avatar for reps.
*
* @param ParamFetcher $paramFetcher
* @param Request $request
*
* @ApiDoc(
* resource = true,
* https = true,
* description = "Set and upload avatar for reps.",
* statusCodes = {
* 200 = "Returned when successful",
* 400 = "Returned when errors"
* }
* )
*
* @RequestParam(name="rid", nullable=false, requirements="\d+", description="The ID of the representative")
* @RequestParam(name="avatar", nullable=false, description="The avatar file")
*
* @return View
*/
public function postRepsAvatarAction(ParamFetcher $paramFetcher, Request $request)
{
$view = View::create();
$uploadedFile = $request->files;
// this is not working I never get that error if I not upload any file
if (empty($uploadedFile)) {
$view->setData(array('error' => 'invalid or missing parameter'))->setStatusCode(400);
return $view;
}
$em = $this->getDoctrine()->getManager();
$entReps = $em->getRepository('PDOneBundle:Representative')->find($paramFetcher->get('rid'));
if (!$entReps) {
$view->setData(array('error' => 'object not found'))->setStatusCode(400);
return $view;
}
.... some code
$repsData = [];
$view->setData($repsData)->setStatusCode(200);
return $view;
}
如果我没有上传文件,则会收到以下响应:
Error: Call to a member function move() on a non-object
500 Internal Server Error - FatalErrorException
但是由于Symfony异常错误不是我想要和需要的JSON,因此代码永远不会输入if
。
如果我没有设置rid
那么我会收到此错误:
Request parameter "rid" is empty
400 Bad Request - BadRequestHttpException
但是再次作为Symfony异常错误而不是JSON。 如果没有rid
或未上传文件,我该如何响应正确的JSON? 有什么建议吗?
$request->files
是FileBag
一个实例。 使用$request->files->get('keyoffileinrequest')
来获取文件。
指定rid
是必需的参数,所以,是的,如果您未设置它,则会抛出BadRequestHttpException。 它的行为应有的表现。 您应该尝试将rid
设置为数据库中没有的ID,然后您将看到自己的错误消息。
如果您希望rid
是可选的,则可以为rid
添加一个默认值:
* @RequestParam(name="rid", nullable=false, requirements="\d+", default=0, description="The ID of the representative")
这样的事情。 现在rid
将为零,您的Repository :: find调用可能会返回null,并且将返回错误视图。 但是我建议您保持原样,这是正确的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.