spring boot 全局异常处理及自定义异常类
全局异常处理:
controller层抛出的自定义异常时,可以实现@ControllerAdvice注解捕获,配合@ExceptionHandler来增强所有的@requestMapping方法。@ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度该注解作用对象为方法,并且在运行时有效,
value()可以指定异常类。异常参数:包括一般的异常或特定的异常(即自定义异常),如果注解没有指定异常类,会默认进行映射。@ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开例如:@ExceptionHandler(Exception.class) 用来捕获@requestMapping的方法中所有抛出的exception。
代码:
@ControllerAdvice
public class GlobalDefultExceptionHandler {
//声明要捕获的异常
@ExceptionHandler(Exception.class)
@ResponseBody
public String defultExcepitonHandler(HttpServletRequest request,Exception e) {
return “error”;
}
}
这样,全局异常处理类完毕。可以添加自己的逻辑。
然后还有一个问题,有的时候,我们需要业务逻辑时抛出自定义异常,这个时候需要自定义业务异常类。
定义class:BusinessException ,使他继承于RuntimeException.
说明:因为某些业务需要进行业务回滚。但spring的事务只针对RuntimeException的进行回滚操作。所以需要回滚就要继承RuntimeException。
public class BusinessException extends RuntimeException{
}
然后,现在来稍微完善一下这个类。
当我们抛出一个业务异常,一般需要错误码和错误信息。有助于我们来定位问题。
所以如下:
1.首先定义一个枚举类型,把错误码及错误信息,组装起来统一管理。
定义一个业务异常的枚举。
public enum ResultEnum {
CODE_200("200", ""),
CODE_400("400", "错误的请求参数"),
CODE_401("401", "没有登录"),
//CODE_402("402", "用户名或密码错误"),
CODE_403("403", "没有权限"),
//CODE_404("404", "用户不存在"),
CODE_405("405", "用户被冻结"),
//CODE_406("406", "信息重复"),
CODE_500("500", "内部服务器错误");
private Integer code;
private String msg;
ResultEnum(Integer code,String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
2.然后定义一个业务异常。
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 1L;
private Integer code; //错误码
public BusinessException() {}
public BusinessException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
3.定义一个全局异常处理类:
@ControllerAdvice
public class GlobalDefultExceptionHandler {
// 根据特定的异常返回指定的 HTTP 状态码400
@ResponseStatus(value=HttpStatus.BAD_REQUEST) // 400
@ExceptionHandler(ConstraintViolationException.class)
public ModelAndView handleValidationException(ConstraintViolationException e) {
logger.error(e.getMessage(),e);
Set<ConstraintViolation<?>> errors = e.getConstraintViolations();
return ResultUtil.error(ResultEnum.CODE_400,errors.toString());
} // 捕捉shiro的异常
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ShiroException.class)
public ModelAndView handleShiroException(HttpServletResponse resp,HttpServletRequest req,ShiroException e) {
logger.error(e.getMessage(),e);
Object errorMassage = req.getAttribute("error"); //取出shiro异常massage
if(errorMassage !=null) { //返回jwt过滤器异常.(这里只是替换错误Massage而已)
return getRedirect(ResultUtil.error(ResultEnum.CODE_401,errors.toString()));
}
return ResultUtil.error(ResultEnum.CODE_401,errors.toString());
} // 捕捉UnauthorizedException
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException.class)
public ModelAndView handleUnauthorizedException(HttpServletResponse resp,HttpServletRequest req,UnauthorizedException e) {
logger.error(e.getMessage(),e);
return ResultUtil.error(ResultEnum.CODE_403,errors.toString());
}
//声明要捕获的异常(自定义异常和Exception)
@ExceptionHandler(Exception.class)
@ResponseBody
public <T> Result<?> defultExcepitonHandler(HttpServletRequest request,Exception e) {
e.printStackTrace();
if(e instanceof BusinessException) {
Log.error(this.getClass(),"业务异常:"+e.getMessage());
BusinessException businessException = (BusinessException)e;
return ResultUtil.error(businessException.getCode(), businessException.getMessage());
}
//未知错误
return ResultUtil.error(-1, "系统异常:\\n"+e);
}
}
判断这个是否是业务异常。和系统异常就可以分开处理了。
spring boot 全局异常处理及自定义异常类的更多相关文章
- Spring Boot全局异常处理
本文为大家分享了Spring Boot全局异常处理,供大家参考,具体内容如下 1.后台处理异常 a.引入thymeleaf依赖 <!-- thymeleaf模板插件 --> <dep ...
- Spring Boot 全局异常处理
Spring Boot版本 1.5 @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExcept ...
- Spring Boot 全局异常配置
Spring Boot 全局异常配置,处理异常控制器需要和发生异常的方法在一个类中.使用 ControllerAdvice 注解 package com.li.controller; import o ...
- spring boot 结合Redis 实现工具类
自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...
- Spring Boot@Component注解下的类无法@Autowired的问题
title: Spring Boot@Component注解下的类无法@Autowired的问题 date: 2019-06-26 08:30:03 categories: Spring Boot t ...
- Spring MVC 全局异常处理&文件上传
Spring MVC 全局异常处理 使用SimpleMappingExceptionResolver实现异常处理 在welcome-servlet.xml进行如下配置: <bean class= ...
- Spring Boot全局支持CORS(跨源请求)
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet. ...
- spring boot全局配置文件优先级
前两篇介绍的application配置文件,即为spring boot全局配置文件.那么spring boot加载配置文件的时候,怎么确定加载哪个目录下哪个文件呢? spring boot默认的配置文 ...
- spring boot的异常处理
原文:https://blog.csdn.net/tianyaleixiaowu/article/details/70145251 全局异常处理是个比较重要的功能,一般在项目里都会用到. 我大概把一次 ...
随机推荐
- 通过ABAP代码判断当前系统类型,BYD还是S4 OP还是S4 Cloud
用工具类 CL_COS_UTILITIES IS_BYD 如果是BYD系统,这个方法的实现会硬编码返回一个true, 在其他系统里则返回false,如图: IS_SUITE 原理同上,suite系统里 ...
- 解释mysql 语句
一.在我们创建mysql数据库的时候我们经常会用到这句SQL: CREATE DATABASE TEST DEFAULT CHARACTER SET utf8 COLLATE utf8_general ...
- 转载-对于Python中@property的理解和使用
原文链接:https://blog.csdn.net/u013205877/article/details/77804137 重看狗书,看到对User表定义的时候有下面两行 @property def ...
- vue-cli3项目中使用CDN
1.html 中引入 echarts html中添加script标签如下: <script src="//cdn.bootcss.com/echarts ...
- C++-cin与scanf cout与printf效率问题
http://blog.csdn.net/l2580258/article/details/51319387 void cin_read_nosync() { freopen("data.t ...
- 关于C++编译时内链接和外链接
最近在阅读<大规模C++ 程序设计> 在第1部分,作者讨论了内链接和外链接问题(因为大规模的C++程序有繁多的类和单元.因此编译速度是个大问题) 这里记录一下关于内链接和外链接的理解. ...
- 最简单之安装azkaban
一,拉取源码构建 git clone https://github.com/azkaban/azkaban.git cd azkaban; ./gradlew build installDist 二, ...
- Bootstrap-轮播图-No.7
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...
- 洛谷P1006 传纸条【dp】
题目:https://www.luogu.org/problemnew/show/P1006 题意: 给定一个m*n的矩阵,从(1,1)向下或向右走到(m,n)之后向上或向左走回(1,1),要求路径中 ...
- 2、docker安装:内核要求、docker三要素、安装、helloworld、底层原理
1.前提说明 1.CentOS Docker 安装 Docker支持以下的CentOS版本: CentOS 7 (64-bit) CentOS 6.5 (64-bit) 或更高的版本 2.前提条件:内 ...