当前位置: 首页 >服务端 > springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler

springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler

前言

本文讲解使用 @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 注解方式实现全 * 局异常处理 */@RestControllerAdvicepublic 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);retu 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);retu 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() {retu this.code;}public final void setCode(int code) {this.code = code;}public final String getMessage() {retu this.message;}public final void setMessage( String message) {this.message = message;}public final PageVO getPage() {retu this.page;}public final void setPage( PageVO page) {this.page = page;}public final Object getData() {retu 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) {retu 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();retu 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();retu this.success(code, message, page, any);}/** * @description 请求成功返回对象 */public final ResponseResultVO success() {retu this.success(null);}/** * @param responseCode  返回的响应码所对应的枚举类 * @description 请求失败返回对象 */public final ResponseResultVO error(ResponseCodeEnum responseCode) {retu new ResponseResultVO(responseCode.getCode(), responseCode.getMessage(), null, null);}/** * @param code  响应码 * @param message相应信息 * @description 请求失败返回对象 */public final ResponseResultVO error(int code, String message) {retu 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() {retu this.code;}public final String getMessage() {retu 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() {retu 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);@Resourceprivate UserInfoMapper userInfoMapper; // maybatis通用Mapper插件 /** * @author 路飞 * @date 2018-8-21 * @param userInfo  用户信息 * @description 保存用户信息 */@Overridepublic 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); }}}

后续会提供代码实例及下载地址。。。

作者:oh路飞
来源链接:https://www.cnblogs.com/topfish/p/9573635.html

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaclub.cn/server/112088.html

标签:异常处理
分享给朋友:

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

划分子网和构造超网的学习 2022年05月17日 13:57:19
软件工程复习要点 2022年05月17日 14:38:01
Logger的级别 2022年05月19日 20:04:12
素数的判断,以及素数的遍历 2022年05月21日 11:41:39
集成极光推送遇到的问题 2022年05月21日 21:05:48
Dart微基准测试第一部分 2022年05月23日 20:48:42
学习go语言国内最全资料链接 2022年05月23日 21:27:32