我有一个带注释的控制器,它包含几个映射在URL上的方法。像这样:
@Controller
public class CategoryController {
@RequestMapping(value = "/addCategories")
public void addCategories(@RequestParam(value = "data") String jsonData) throws ParseException
@RequestMapping(value = "/getNext")
public void getNext(@RequestParam(value = "data") String jsonData) throws ParseException
...
}
方法需要解析json请求并执行一些操作。解析请求可能会生成已检查的ParseException
,我可以在方法中处理或将throws
添加到其签名中。我更喜欢第二种方法,因为在这里我不想在代码中添加额外的try / catch。
那么问题是如何为控制器方法配置和编码处理程序?
答案 0 :(得分:3)
您应查看@ExceptionHandler
的弹簧文档。
@Controller
public class CategoryController {
@ExceptionHandler(ParseException.class)
public ModelAndView handleParseExc(ParseException ex) {
//...
}
@RequestMapping(value = "/addCategories")
public void addCategories(@RequestParam(value = "data") String jsonData) throws ParseException
}
或者子类AbstractHandlerExceptionResolver
,如果要为所有控制器处理这些异常,请在xml配置中将其声明为spring mvc bean。