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

spring框架做全局异常捕获_@ControllerAdvice注解(全局异常捕获)

时间:2019-06-19 13:42:06

相关推荐

spring框架做全局异常捕获_@ControllerAdvice注解(全局异常捕获)

背景

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

@ExceptionHandler异常处理器

作用:可以拦截程序抛出来的指定异常。使用场景:主要使用与项目统一异常处理,对于rest风格的返回统一异常格式。

/** * 指定拦截异常的类型 * * @param e * @return json格式类型 */@ExceptionHandler({Exception.class}) //指定拦截异常的类型 @ResponseBody public 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

自定义参数验证器使用传送门:SpringBoot自定义参数验证器

@ModelAttribute

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

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

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

获取参数:

@GetMapping("test") @ResponseBody public 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}) //指定拦截异常的类型 @ResponseBody public 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*/ @InitBinder public void initWebBinder(WebDataBinder binder) { //对日期的统一处理// binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); //添加对数据的校验 //binder.setValidator(); } /*** 把值绑定到Model中,使全局@RequestMapping可以获取到该值** @param model*/ @ModelAttribute public void addAttribute(Model model) { model.addAttribute("msg", "hello"); }}

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

转载自GoslingWu,未经许可,严禁抄袭

更多相关内容,Java&python,软件开发等学习资料,电子书及视频还有高级讲师免费课程,

需要的可以私聊小编发送【学习】二字

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