我正在POST
为 RESTful API 制作一种方法。如您所见,该 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 ?有什么建议吗?