2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

@RequestBodyと@Validの両方を利用時に"The request sent by the client was syntactically incorrect"が出る

Posted at

残業続きで眠いです……。誤字脱字は勘弁してね(´・ω・`)

クライアントからPOSTされたJSONを受け取って、JSONを返すようなコントローラの開発中、POSTされるJSONを何かしらのBeanにマッピングさせ、かつBeanValidationを機能させたいとします。

@Controller
public HogeController {

    @RequestMapping(path="/hoge", 
                    method=RequestMethod.POST,
                    consumes=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, String> hoge(@RequestBody @Valid JsonBean jsonBean)
        // do something
    }
}

このときJsonBeanに設定されたBean Validatorが機能して、JSONがBeanにマッピングされない場合、そのメソッドの中(上記の例ではhogeメソッドの中)には入っていきません。つまりクライアント側にはJSONが返されず、次のようなエラーメッセージを持ったHTMLが返されてしまうのです。

Error 400 The request sent by the client was syntactically incorrect

対処法としては__MethodArgumentNotValidExceptionを受けるExceptionHandlerを設定する__ことです。


@Controller
public HogeController {

    @RequestMapping(path="/hoge", 
                    method=RequestMethod.POST,
                    consumes=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, String> hoge(@RequestBody @Valid JsonBean jsonBean)
        // do something
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Map<String, String> hogeHandler(MethodArgumentNotValidException e){
        // do something
    }
}

こうすることにより、POSTされたJSONがBeanにマッピングされない場合は、MethodArgumentNotValidExceptionを受けるExceptionHandler(上記の例ではhogeHandler)が実行されます。つまりマッピングされない場合にクライアントに返したいJSONをこのExceptionHandlerの戻り値にしてやればよいということになります。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?