Ошибка возврата объекта FOSRestBundle

1

Я использую FOERestBundle и класс View. И когда я проверяю объект, у меня есть объектная ошибка, подобная этой, и это:

[
 {
   "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."
 }
]

Мне нужна ошибка возвращаемого объекта, когда пользователь недействительный маркер безопасности как это

[
 {
   "property_path": "main_skill",
   "message": "This value should not be blank."
 },
]

теперь у меня есть простой текст. Это моя конечная точка

    /**
 * 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);
    }
}

теперь у меня есть обычный текст

Response Body [Raw]
"Secret token is not valid"

это ошибка возврата объекта-объекта, и это нормально

[
 {
   "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."
 }
]

Как вернуть пользовательскую ошибку, как объект, а не обычный текст?

Теги:
validation
fosrestbundle

2 ответа

1
Лучший ответ

Просто передайте свои данные, как массив, и скажите, как это сделать, поскольку json должен генерировать вывод, как вы хотели

$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);
0

Вы можете использовать Symfony HTTPExceptions, поскольку они будут обрабатываться FOSRestBundle.

См. Http://symfony.com/doc/current/bundles/FOSRestBundle/4-exception-controller-support.html.

public function putBitAction(Request $request, $id)
{
    $token = $request->get('token');
    if (null === $token) {
        throw new BadRequestHttpException('Provide a secret token');
    }

    $manager = $this->getDoctrine()->getManager();
    $user = $manager->getRepository('MyBundle:Users')->findOneBySecuritytoken($token);
    if (null === $user) {
        throw new BadRequestHttpException('Secret token is not valid');
    }        

    $bit = $manager->getRepository('MyBundle:Bit')->find($id);
    if (null === $token) {
        throw new NotFoundHttpException('Bid not found');
    }

    $view = $this->view($bit, 200);
    return $this->handleView($view);
}

И как это запрос PUT? Вы должны переименовать это в getBidAction.

  • 0
    Я поставил логику. И у меня есть в prod twig: exception_controller: ArtelProfileBundle: Exception: showException this action = return $ this-> redirect ($ this-> generateUrl ('login_route'))); И BadRequestHttpException, NotFoundHttpException не возвращаются в prod в prod, возвращают login_page, но видят работу в prod очень хорошо

Ещё вопросы

Сообщество Overcoder
Наверх
Меню