我的控制器具有根据其@RequestMapping(produce ="",consume ="")注释生成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");
}
Run Code Online (Sandbox Code Playgroud)
如何为上述两种方法编写@ExceptionHandler?非JSON的那个应该添加一个属性Model.
model.addAttribute("error", exception.getMessage());
Run Code Online (Sandbox Code Playgroud)
具有JSON响应类型的那个应该将错误返回为a Map,以便稍后序列化为JSON.
我尝试了下面但春天不喜欢用相同的异常类型声明的两个不同的@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;
}
Run Code Online (Sandbox Code Playgroud)
你们俩都有ExceptionHandler争论RuntimeException。因此,在您的情况下,只有 1exceptionhandler受到尊重。
我不确定你在做什么。但我想自己写一下exceptionresolver可以解决你的问题。我已经这样做了。我创建了自己的exceptionresolver专用于 Ajax 请求的文件,然后将其与现有的ExceptionHandlerExceptionResolver.
| 归档时间: |
|
| 查看次数: |
2855 次 |
| 最近记录: |