说在前面
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中
说明
@ControllerAdvice
该注解是spring3.2以后新增的一个注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,作用于@RequestMapping标注的方法上。可指定扫描范围。
@ExceptionHandler
该注解是配合@ExceptionHandler一起使用的注解,自定义错误处理器,可自己组装json字符串,并返回到页面。
代码实现
/**
* 捕获全局异常
* @author zlzhaoe
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常处理
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String, Object> exceptionHandler(Exception ex) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("errorCode", "500");
map.put("message", ex.getMessage());
map.put("errorMsg", "后台错误,请联系管理员!");
return map;
}
}