前言

本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用在 Controller 层进行 try-catch 了
     代码示例地址(代码里面类名稍微有些不同): https://gitee.com/coderLOL/springboot-demos

一、处理思路

  1. 思路:在sevice业务逻辑层 try{}catch(){} 捕获抛出,经由contorller 层抛到 自定义全局处理类 中处理自定义异常及系统异常。

2、实现方式:使用 @RestControllerAdvice + @ExceptionHandler 注解方式实现全局异常处

二、实现过程

1、@ControllerAdvice 注解定义全局异常处理类 ,@ExceptionHandler 注解声明异常处        理方法。

( 本类方法中用到的 ResponseResultUtil 工具类, ResponseCodeEnum 枚举类,下面步骤中会介绍)

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; /**
* @author 路飞
* @date 2018-8-21
* @description 全局异常处理: 使用 @RestControllerAdvice + @ExceptionHandler 注解方式实现全
* 局异常处理
*/
@RestControllerAdvice
public class GlobalExceptionHandler { private final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class); /**
* @author 路飞
* @date 2018-8-22
* @param e 异常
* @description 处理所有不可知的异常
*/
@ExceptionHandler({Exception.class}) //申明捕获那个异常类
public ResponseResultVO globalExceptionHandler(Exception e) {
this.logger.error(e.getMessage(), e);
return new ResponseResultUtil().error(ResponseCodeEnum.OPERATE_FAIL);
} /**
* @author 路飞
* @date 2018-8-21
* @param e 异常
* @description 处理所有业务异常
*/
@ExceptionHandler({BaseBusinessException.class})
public ResponseResultVO BusinessExceptionHandler(BaseBusinessException e) {
this.logger.error(e);
return new ResponseResultUtil().error(e.getCode(), e.getMessage());
} }

2、定义一个用于返回页面结果信息的VO对象类:ResponseResultVO

/**
* @author 路飞
* @date 2018-8-21
* @description 请求响应对象
*/
public final class ResponseResultVO<T> {
/**
* @description 响应码
*/
private int code; /**
* @description 响应消息
*/
private String message; /**
* @description 分页对象 (如果用不到,这个可以不写)
*/
private PageVO page; /**
* @description 数据
*/
private Object data; public final int getCode() {
return this.code;
} public final void setCode(int code) {
this.code = code;
} public final String getMessage() {
return this.message;
} public final void setMessage( String message) {
this.message = message;
} public final PageVO getPage() {
return this.page;
} public final void setPage( PageVO page) {
this.page = page;
} public final Object getData() {
return this.data;
} public final void setData(Object data) {
this.data = data;
} public ResponseResultVO(int code, String message, PageVO page, Object data) {
super();
this.code = code;
this.message = message;
this.page = page;
this.data = data;
} }

3、 定义一个对步骤2中 返回信息结果处理的工具类:ResponseResultUtil

/**
* @author zhangwenlong
* @date 2018-8-20
* @description 请求响应工具类
*/
public final class ResponseResultUtil { /**
* @param code 响应码
* @param message 相应信息
* @param any 返回的数据
* @description 请求成功返回对象
*/
public final ResponseResultVO success(int code, String message, PageVO page, Object any) {
return new ResponseResultVO(code, message, page, any);
} /**
* @param any 返回的数据
* @description 请求成功返回对象
*/
public final ResponseResultVO success(Object any) {
int code = ResponseCodeEnum.SUCCESS.getCode();
String message = ResponseCodeEnum.SUCCESS.getMessage();
return this.success(code, message, null, any);
} /**
* @param any 返回的数据
* @description 请求成功返回对象
*/
public final ResponseResultVO success(Object any, PageVO page) {
int code = ResponseCodeEnum.SUCCESS.getCode();
String message = ResponseCodeEnum.SUCCESS.getMessage();
return this.success(code, message, page, any);
} /**
* @description 请求成功返回对象
*/
public final ResponseResultVO success() {
return this.success(null);
} /**
* @param responseCode 返回的响应码所对应的枚举类
* @description 请求失败返回对象
*/
public final ResponseResultVO error(ResponseCodeEnum responseCode) {
return new ResponseResultVO(responseCode.getCode(), responseCode.getMessage(), null, null);
} /**
* @param code 响应码
* @param message 相应信息
* @description 请求失败返回对象
*/
public final ResponseResultVO error(int code, String message) {
return new ResponseResultVO(code, message, null, null);
}
}

4、为方便统一管理异常代码和信息之间的关系,建立枚举类: ResponseCodeEnum

/**
* @author 路飞
* @date 2018-8-20
* @description 响应码配置枚举
*/
public enum ResponseCodeEnum {
// 系统通用
SUCCESS(200, "操作成功"), UNLOGIN_ERROR(233, "没有登录"), OPERATE_FAIL(666, "操作失败"), // 用户
SAVE_USER_INFO_FAILED(2001, "保存用户信息失败"), GET_USER_INFO_FAILED(2002, "保存用户信息失败"), WECHAT_VALID_FAILED(2003, "微信验证失败"), GET_USER_AUTH_INFO_FAILED(2004, "根据条件获取用户授权信息失败"), SAVE_USER_AUTH_INFO_FAILED(2005, "保存用户授权失败"); private Integer code;
private String message; ResponseCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
} public final Integer getCode() {
return this.code;
} public final String getMessage() {
return this.message;
} }

5、

(1)封装一个基础业务异常类(让所有自定义业务异常类 继承此 基础类):BaseBusinessException

/**
* @author zhangwenlong
* @date 2018-8-21
* @description 价值分析系统所有的 业务异常父类
*/
public class BaseBusinessException extends RuntimeException { private Integer code; // 给子类用的方法
public BaseBusinessException(ResponseCodeEnum responseCodeEnum) {
this(responseCodeEnum.getMessage(), responseCodeEnum.getCode());
} private BaseBusinessException(String message, Integer code) {
super(message);
this.code = code;
} public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
}
}

(2)自定义的业务异常类 (例如):

自定义用户异常

/**
* @author 路费
* @date 2018-8-21
* @description 自定义用户异常
*/
public class UserException extends BaseBusinessException { // 继承继承 业务异常类
public UserException(ResponseCodeEnum responseCodeEnum) {
super(responseCodeEnum);
}
}

6、service 层抛出

/**
* @author 路飞
* @date 2018-8-21
* @description 用户信息业务接口实现类
*/
@Service("userInfoService")
public class UserInfoSerimpl implements UserInfoService { private Logger logger = LoggerFactory.getLogger(UserInfoSerimpl.class); @Resource
private UserInfoMapper userInfoMapper; // maybatis通用Mapper插件 /**
* @author 路飞
* @date 2018-8-21
* @param userInfo 用户信息
* @description 保存用户信息
*/
@Override
public void saveUserInfo(UserInfo userInfo) {
try {
userInfoMapper.insertSelective(userInfo);
} catch (Exception e) {
logger.error("获取用户信息失败", e);
//抛出自定义异常: ResponseCodeEnum.SAVE_USER_INFO_FAILED
throw new UserException(ResponseCodeEnum.SAVE_USER_INFO_FAILED);
}
} }

springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler的更多相关文章

  1. SpringBoot全局异常拦截

    SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...

  2. SpringBoot项目中的全局异常处理器 Failed to invoke @ExceptionHandler method

    文件下载代码 @RequestMapping(value = { "/data/docking/picture/{id}/{empi}" }) public JsonApi pic ...

  3. springboot 全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  4. SpringBoot 全局异常配置

    在日常web开发中发生了异常,往往是需要通过一个统一的异常处理来保证客户端能够收到友好的提示. 一.默认异常机制 默认异常处理(SpringBoot 默认提供了两种机制,一种是针对于web浏览器访问的 ...

  5. SpringBoot处理异常方式

    SpringBoot提供了多种处理异常方式,以下为常用的几种 1. 自定义错误异常页面 SpringBoot默认的处理异常的机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序中出现 ...

  6. 自定义Springboot全局异常类

    一.简要说明 如何实现网上文章基本是随便一搜就可以很快找到, 这里不再赘述. 二.Spring-web和Spring-webmvc 通过idea查看到两个注解位于 spring-web-5.2.2.R ...

  7. SpringBoot 全局异常拦截捕获处理

    一.全局异常处理 //Result定义全局数据返回对象 package com.xiaobing.demo001.domain; public class Result { private Integ ...

  8. Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获

    一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.ex ...

  9. springboot全局异常拦截源码解读

    在springboot中我们可以通过注解@ControllerAdvice来声明一个异常拦截类,通过@ExceptionHandler获取拦截类抛出来的具体异常类,我们可以通过阅读源码并debug去解 ...

随机推荐

  1. Ubuntu16.04更新源

    首先说说为什么要更新源,我是在docker容器中修改配置文件时有所需要,要用到vim,但是会报错.找不到需要的包. 网上都会说要先更新:apt-get update 但是超级慢有没有,我更新了4小时, ...

  2. LAB1 partII

    PartII   实现单词统计 实现 main/wc.go 两个函数 mapF() . reduceF() 单词是任意字母连续序列, 由unicode.IsLetter 决定字母 测试数据 pg-*. ...

  3. note 7 递归函数

    递归:程序调用自身 形式:在函数定义有直接或间接调用自身 阶乘:N!=123...N def p(n): x = 1 i = 1 while i <= n: x = x * i i = i + ...

  4. 2018-2019-2 20165312《网络攻防技术》Exp1 PC平台逆向破解

    2018-2019-2 20165312<网络攻防技术>Exp1 PC平台逆向破解 一.Exp1.1 直接修改程序机器指令,改变程序执行流程 知识要求:Call指令,EIP寄存器,指令跳转 ...

  5. ionic2 vscode运行调试

    一.环境搭建 1,安装ripple模拟器 如果已经注册了淘宝国内镜像使用下面命令 cnpm install -g ripple-emulator 显示结果如下: 2,安装vs code 下载地址htt ...

  6. 转发:VB程序操作word表格(文字、图片)

    很多人都知道,用vb操作excel的表格非常简单,但是偏偏项目中碰到了VB操作word表格的部分,google.baidu搜爆了,都没有找到我需要的东西.到是搜索到了很多问这个问题的记录.没办法,索性 ...

  7. php redis 操作

    在php里边,redis就是一个功能类,该类中有许多成员方法(名字基本与redis指令的名字一致,参数也一致). 实例: <?php $redis = new Redis(); //连接本地的  ...

  8. c语言中变量和函数作用域深究

    首先,函数的作用域和访问权限基本可以参考 C语言中的作用域,链接属性和存储类型 也存在例外情况,比如内联函数 static inline,使用static 修饰 inline之后外部文件也可以访问内联 ...

  9. Python Queue(队列)

    Queue模块实现了多生产者.多消费者队列.当必须在多个线程之间安全地交换信息时,它在线程编程中特别有用,实现了所有必需的锁定语义. 一.该模块实现了三种类型的队列,它们的区别仅在于检索条目的顺序: ...

  10. JAVA正则表达式匹配,替换,查找,切割(转)

    import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public c ...