1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > @ControllerAdvice注解(全局异常捕获)

@ControllerAdvice注解(全局异常捕获)

时间:2022-04-13 08:32:45

相关推荐

@ControllerAdvice注解(全局异常捕获)

背景

@ControllerAdvice 注解 通常用于定义@ExceptionHandler@InitBinder@ModelAttribute适用于所有@RequestMapping方法的方法。

@ExceptionHandler异常处理器

作用:

可以拦截程序抛出来的指定异常。

使用场景:

主要使用与项目统一异常处理,对于rest风格的返回统一异常格式。

/*** 指定拦截异常的类型** @param e* @return json格式类型*/@ExceptionHandler({Exception.class}) //指定拦截异常的类型@ResponseBodypublic Object customExceptionHandler(Exception e) {//打印异常日志e.printStackTrace();//非空验证异常if(e instanceof BindException){BindException bindException = (BindException) e;String msg = bindException.getBindingResult().getFieldError().getDefaultMessage();return msg;}if(e instanceof GlobalException){GlobalException globalException = (GlobalException) e;return globalException.getErrMsg();}return "系统异常";}

@InitBinder

作用:

应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器

使用场景:

1.可用于绑定作用于全局的请求参数验证器。

2.日期格式把请求中的日期字符串转换成Date类型。

/*** 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器** @param binder*/@InitBinderpublic void initWebBinder(WebDataBinder binder) {//对日期的统一处理// binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));//添加对数据的校验//binder.setValidator();}

自定义参数验证器使用传送门:/p/518a45c3d72f

@ModelAttribute

作用:

把值绑定到Model中,使全局@RequestMapping可以获取到该值

使用场景:

大家发挥自己那聪明的小脑袋吧,本人也没想到哪里实战使用!

/*** 把值绑定到Model中,使全局@RequestMapping可以获取到该值** @param model*/@ModelAttributepublic void addAttribute(Model model) {model.addAttribute("msg", "hello");}

获取参数:

@GetMapping("test")@ResponseBodypublic Object test(@ModelAttribute("msg") String msg){return msg;}

完整的代码

package com.wzq.config.exception;import org.springframework.ui.Model;import org.springframework.validation.BindException;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.*;/*** @description: 全局异常处理类* @author: Wzq* @create: -12-26 11:01*/@RestControllerAdvicepublic class GlobalExceptionAdvice {/*** 指定拦截异常的类型** @param e* @return json格式类型*/@ExceptionHandler({Exception.class}) //指定拦截异常的类型@ResponseBodypublic Object customExceptionHandler(Exception e) {//打印异常日志e.printStackTrace();//非空验证异常if(e instanceof BindException){BindException bindException = (BindException) e;String msg = bindException.getBindingResult().getFieldError().getDefaultMessage();return msg;}if(e instanceof GlobalException){GlobalException globalException = (GlobalException) e;return globalException.getErrMsg();}return "系统异常";}/*** 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器** @param binder*/@InitBinderpublic void initWebBinder(WebDataBinder binder) {//对日期的统一处理// binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));//添加对数据的校验//binder.setValidator();}/*** 把值绑定到Model中,使全局@RequestMapping可以获取到该值** @param model*/@ModelAttributepublic void addAttribute(Model model) {model.addAttribute("msg", "hello");}}

@RestControllerAdvice 和 @ControllerAdvice区别在于@RestControllerAdvice不需要加@ResponseBody

个人微信公众,经常更新一些实用的干货:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。