简介
@ControllerAdvice注解是用来增强的Controller。可以实现三个方面功能:
全局异常处理
全局数据绑定
全局数据预处理
全局异常处理
针对计算类型错误进行处理
@ControllerAdvice
public class MyControllerAdvice {
@ResponseBody
@ExceptionHandler({ArithmeticException.class})
public Map arithmeticException(ArithmeticException e, HttpServletResponse resp) {
Map map = new HashMap<>();
map.put("code", 500);
map.put("msg", e.getMessage());
return map;
}
}
统一参数预处理
前端时间单位用的是unix时间戳,单位秒,而java后端用的是Date类型。
在request请求时,如何把前端的时间戳类型优雅的转换为后端的Date类型呢。
@ControllerAdvice
public class MyControllerAdvice {
@InitBinder
public void initWebBinder(WebDataBinder binder) {
//对日期的统一处理
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//添加对数据的校验
//binder.setValidator();
}
}