私のコントローラーには、 @RequestMapping(produces="", consumers="") アノテーションに応じて JSON または HTML を生成するメソッドがあります。ただし、一般的な方法で例外を処理することになると、問題に直面しています。
@RequestMapping(method = POST)
public String add(@Valid MyForm form, BindingResult result, Model model) {
if (result.hasErrors()) {
return "edit";
}
throw new RuntimeException("Error adding");
return "edit";
}
@RequestMapping(method = POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public Map<String, Object> addJSON(@RequestBody @Valid MyForm form, Model model) {
throw new RuntimeException("Error adding");
}
上記の 2 つのメソッドに対して @ExceptionHandler を記述するにはどうすればよいですか? 非 JSON 用のものは、に属性を追加する必要がありますModel
。
model.addAttribute("error", exception.getMessage());
JSON 応答タイプを持つものは、エラーを として返し、Map
後で JSON にシリアル化する必要があります。
私は以下を試しましたが、同じ例外タイプで宣言された 2 つの異なる @ExceptionHandler 注釈付きメソッドが春には好きではありません。
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@RequestMapping(produces = "application/json")
@ResponseBody
public Map<String, Object> handleExceptionAsJSON(RuntimeException exception) {
Map<String, Object> map = new HashMap<>();
map.put("error", exception.getMessage());
return map;
}
@ExceptionHandler(RuntimeException.class)
public Map<String, Object> handleException(RuntimeException exception) {
Map<String, Object> map = new HashMap<>();
map.put("error", exception.getMessage());
return map;
}