如何为来自 FOSRestBundle 的 RESTful API 中的 POST 方法设置正确的 JSON 响应?

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->filesFileBag 的实例。使用 $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 调用可能 return 为空并且您的错误视图将被 returned。但我建议您保持原样,这是正确的行为。