douhe3313 2016-02-08 15:06
浏览 71
已采纳

Symfony Assert DateTime JMSSerializer

I have endpoint postOrder - create entity order. In entity order I have fields with type DateTime and I want when somebody write string instead DateTime I have "Not valid, should be DateTime" . For other fields I use like this

 * @Assert\Length(min=3, max=255)

or

 * @Assert\Regex(
 *           pattern= "/^[\d() \-+]+$/",
 *           message= "This text cannot contain numbers"
 * )

or

     * @Assert\NotBlank()

I get all request then serialize then deserialize for concrete entity when validate and have information from assert in endpoint, but for DateTime this not work I use FosRestBundle and JMSSerializer this is my action

 /**
 * Post Order.
 *
 * @ApiDoc(
 * resource = true,
 * description = "Post Order",
 *  parameters={
 *      {"name"="comment", "dataType"="string", "required"=false, "description"="comment"},
 *      {"name"="interview_date", "dataType"="date", "required"=false, "description"="date conect for developer"},
 *      {"name"="contact_date", "dataType"="date", "required"=false, "description"="date contact fir TIM"}
 *
 *  },
 * statusCodes = {
 *      200 = "Returned when successful",
 *      400 = "Returned secret token is not valid"
 * },
 * section="Order"
 * )
 *
 * @RestView()
 *
 * @param Request $request
 *
 * @return View
 *
 * @throws NotFoundHttpException when not exist
 */
public function postOrderAction(Request $request)
{
        $data = $request->request->all();
        $data = $this->get('serializer')->serialize($data, 'json');
        $serviceLead = $this->get('serializer')->deserialize($data, 'Artel\ProfileBundle\Entity\CodeServiceLead', 'json');
        $errors = $this->get('validator')->validate($serviceLead);
            if (count($errors) > 0) {
                $view = $this->view($errors, 400);

                return $this->handleView($view);
            }

and fields

class Orders
{


    /**
 * @var string
 *
 * @ORM\Column(name="comment", type="string", nullable=true)
 * @Groups({"get_all_orders_admin", "get_all_orders", "for_vip"})
 */
protected $comment;

    /**
 * @var \DateTime
 * @ORM\Column(name="interview_date", type="date", nullable=true)
 * @Groups({"get_all_orders_admin", "get_all_orders", "for_vip"})
 * @Assert\DateTime()
 */
protected $interview_date;

/**
 * @var \DateTime
 * @ORM\Column(name="contact_date", type="date", nullable=true)
 * @Groups({"get_all_orders_admin", "get_all_orders", "for_vip"})
 * @Assert\DateTime()
 */
protected $contact_date;

Now I have error when I try deserialize for entity order

{
"error": {
"code": 500,
"message": "Internal Server Error",
"exception": [
  {
    "message": "Invalid datetime \"some_string\", expected format Y-m-d\\TH:i:sO.",
    "class": "JMS\\Serializer\\Exception\\RuntimeException",

How to return correct error or assert, without 500, in this situation ?

  • 写回答

1条回答 默认 最新

  • dongzao4503 2016-02-08 15:57
    关注

    When you call deserialize(), that is already checking your entity for validity against your Doctrine annotations since the JMS Serializer already integrates with the Doctrine ORM.

    If deserializing fails, an exception is thrown, which is what you are seeing.

    All you need to do in your case is put your code in a try/catch block if you want to handle that yourself:

    public function postOrderAction(Request $request)
    {
        $data = $request->request->all();
        $data = $this->get('serializer')->serialize($data, 'json');
    
        try {
            $serviceLead = $this->get('serializer')->deserialize(
                $data,
                'Artel\ProfileBundle\Entity\CodeServiceLead',
                'json'
            );
        } catch (\Exception $e) {
            $view = $this->view((array) $e->getMessage(), 400);
    
            return $this->handleView($view);
        }
    }
    

    I didn't see your view() function but I assumed it was expecting an array of strings of error messages so I cast exception message to an array. Either way you get the idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)