1.什么是全局异常拦截器
- 从实际使用来看,可以理解成是使用aop技术进行的环绕增强,在执行前可以将一些数据绑定到model或者屏蔽某些字段,在业务逻辑执行后可以执行业务是否有异常并且进行拦截
2.一般使用场景
较多的用处是用来做全局的异常处理,将某些不友好的信息稍微加工变成较为友好的信息输出
3.开始使用全局异常拦截器
- 实现使用@ControllerAdvice声明一个建言
- 使用@ExceptionHandler(xxx.class)可以捕获需要的异常或者运行时异常,之后再进行处理
- 使用@ModelAttribute,将键值对添加到全局,所有注解了@RequestMapping都可以获得此键值对
- 使用@InitBinder,可以定制WebDataBinder
/**
* 全局的的异常拦截器(拦截所有的控制器)(带有@RequestMapping注解的方法上都会拦截)
*
* @author fengshuonan
* @date 2016年11月12日 下午3:19:56
*/
@ControllerAdvice
@Order(-1)
public class GlobalExceptionHandler {
private Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 拦截业务异常
*/
@ExceptionHandler(ServiceException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponseData bussiness(ServiceException e) {
LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
getRequest().setAttribute("tip", e.getMessage());
log.error("业务异常:", e);
return new ErrorResponseData(e.getCode(), e.getMessage());
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponseData notFount(RuntimeException e) {
LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
getRequest().setAttribute("tip", "服务器未知运行时异常");
log.error("运行时异常:", e);
return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(), BizExceptionEnum.SERVER_ERROR.getMessage());
}
@ModelAttribute
public void addAttribute(Model model){
model.addAttribute("llg","李利光");
}
@InitBinder
public void initBinder(WebDataBinder webDataBinder){
webDataBinder.setDisallowedFields("id");
}
}