1

我正在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 ?有什么建议吗?

4

1 回答 1

2

$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 并且您的错误视图将被返回。但我建议你保持原样,这是正确的行为。

于 2015-05-30T12:02:11.150 回答