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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应