Spring的@ExceptionHandler和@ControllerAdvice统一处理异常
之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch
try{
..........
}catch(Exception1 e){
..........
}catch(Exception2 e){
...........
}catch(Exception3 e){
...........
}
这样其实代码既不简洁好看 ,我们敲着也烦, 一般我们可能想到用拦截器去处理, 但是既然现在Spring这么火,AOP大家也不陌生, 那么Spring一定为我们想好了这个解决办法.果然: @ExceptionHandler
源码
//该注解作用对象为方法
@Target({ElementType.METHOD})
//在运行时有效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
//value()可以指定异常类
Class<? extends Throwable>[] value() default {};
}
@ControllerAdvice
源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//bean对象交给spring管理生成
@Component
public @interface ControllerAdvice {
@AliasFor("basePackages")
String[] value() default {};
@AliasFor("value")
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
Class<?>[] assignableTypes() default {};
Class<? extends Annotation>[] annotations() default {};
}
从名字上可以看出大体意思是控制器增强
所以结合上面我们可以知道,使用@ExceptionHandler,可以处理异常, 但是仅限于当前Controller中处理异常, @ControllerAdvice可以配置basePackage下的所有controller. 所以结合两者使用,就可以处理全局的异常了.
1.定义一个异常
public class CustomGenericException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public CustomGenericException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}
2. 定义一个controller
这里我们就不用try catch了, 直接抛异常就可以了
@Controller
@RequestMapping("/exception")
public class ExceptionController {
@RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
if ("error".equals(type)) {
// 由handleCustomException处理
throw new CustomGenericException("E888", "This is custom message");
} else if ("io-error".equals(type)) {
// 由handleAllException处理
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
}
3.异常处理类
这个类就可以当做controller类写了, 返回参数跟mvc返回参数一样
@ControllerAdvice
public class ExceptionsHandler {
@ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ //还可以声明接收其他任意参数
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errCode",exception.getErrCode());
modelAndView.addObject("errMsg",exception.getErrMsg());
return modelAndView;
}
//可以通过ResponseStatus配置返回的状态码
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)//可以直接写@EceptionHandler,IOExeption继承于Exception
public ModelAndView allExceptionHandler(Exception exception){
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errMsg", "this is Exception.class");
return modelAndView;
}
}
4.jsp页面
正常的页面
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Spring MVC @ExceptionHandler Example</h2>
<c:if test="${not empty msg}">
<h2>${msg}</h2>
</c:if>
</body>
</html>
异常处理页面
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<c:if test="${not empty errCode}">
<h1>${errCode} : System Errors</h1>
</c:if>
<c:if test="${empty errCode}">
<h1>System Errors</h1>
</c:if>
<c:if test="${not empty errMsg}">
<h2>${errMsg}</h2>
</c:if>
</body>
</html>
Spring的@ExceptionHandler和@ControllerAdvice统一处理异常的更多相关文章
- @ExceptionHandler和@ControllerAdvice统一处理异常
//@ExceptionHandler和@ControllerAdvice统一处理异常//统一处理异常的controller需要放在和普通controller同级的包下,或者在ComponentSca ...
- @ControllerAdvice与@ControllerAdvice统一处理异常
https://blog.csdn.net/zzzgd_666/article/details/81544098(copy) 详细看此 所以结合上面我们可以知道,使用@ExceptionHandler ...
- Spring异常处理@ExceptionHandler
最近学习Spring时,认识到Spring异常处理的强大.之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑: try{ ... ...
- spring boot:使接口返回统一的RESTful格式数据(spring boot 2.3.1)
一,为什么要使用REST? 1,什么是REST? REST是软件架构的规范体系,它把资源的状态用URL进行资源定位, 以HTTP动作(GET/POST/DELETE/PUT)描述操作 2,REST的优 ...
- 【统一异常处理】@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
1.利用springmvc注解对Controller层异常全局处理 对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service ...
- @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常==》记录
对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...
- 转:@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,并且可以返回自定义格式: 复制代码 1 @Slf4j 2 @ControllerAdv ...
- 只需一步,在Spring Boot中统一Restful API返回值格式与统一处理异常
## 统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生. 比较通用的返回值格式如下: ```jav ...
- Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理
本文完整代码下载点击 一. 前言 相信了解过我或者看过我之前的系列文章应该多少知道点我写这些文章包括创建 有来商城youlai-mall 这个项目的目的,想给那些真的想提升自己或者迷茫的人(包括自己- ...
随机推荐
- 【Python】编程小白的第一本python(基础中的基础)
一.变量 如果不知道变量是什么类型,可以通过type()函数来查看类型,在IDE中输入: print(type(word)) 另外,由于中文注释会导致报错,所以需要在文件开头加一行魔法注释 #codi ...
- 【小技巧】O(1)快速乘
问题:求 \(a\times b\bmod p\),\(a,b,p\) 在 long long 范围内. 在 CRT 等算法中应用广泛. 为了处理模数在 int 范围外的情况,就是两数相乘可能会爆 l ...
- pycharm flask debug调试接口
pycharm中对某接口调试,使用print打印日志太麻烦,可以通过debug模式来调试 一.首先开启flask的debug开关 编辑configurations 勾选FLASK_DEBUG选项 已d ...
- LeetCode 321. Create Maximum Number
原题链接在这里:https://leetcode.com/problems/create-maximum-number/description/ 题目: Given two arrays of len ...
- 微信扫描二维码跳转手机默认浏览器打开下载app的链接是怎么实现的
此方法可以实现微信内置浏览器跳转到手机其它浏览器,现在网上其它的方法都只是一个页面,让访问者自己手动点右上角浏览器打开,而这个不同,是可以直接自动跳转的. <?php error_reporti ...
- BZOJ 5093: [Lydsy1711月赛]图的价值 第二类斯特林数+NTT
定义有向图的价值为图中每一个点的度数的 \(k\) 次方之和. 求:对于 \(n\) 个点的无向图所有可能情况的图的价值之和. 遇到这种题,八成是每个点单独算贡献,然后累加起来. 我们可以枚举一个点的 ...
- LibreOJ #6212. 「美团 CodeM 决赛」melon
二次联通门 : LibreOJ #6212. 「美团 CodeM 决赛」melon /* LibreOJ #6212. 「美团 CodeM 决赛」melon MDZZ 这是决赛题?? */ #incl ...
- python 链表的实现
code #!/usr/bin/python # -*- coding: utf- -*- class Node(object): def __init__(self,val,p=): self.da ...
- ubuntu 14.04 系统配置磁盘,CPU,内存,硬盘信息查看
Linux查看物理CPU个数.核数.逻辑CPU个数# 总核数 = 物理CPU个数 X 每颗物理CPU的核数 # 总逻辑CPU数 = 物理CPU个数 X 每颗物理CPU的核数 X 超线程数 查看分区磁盘 ...
- BAT 定时将多个本地文件同步到共享目录
copy.bat 具体执行脚本,需要修改共享目录访问用户名,密码,同步的文件类型 list.txt 前面为本地文件夹,后面为共享目录,中间以”,”进行分割 附件地址: https://files. ...