别再写满屏的 try catch 了,教你如何统一处理异常!

2023-12-10 23:30

本文主要是介绍别再写满屏的 try catch 了,教你如何统一处理异常!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在开发过程中,不可避免的是需要处理各种异常,所以代码中就会出现大量的try {...} catch {...} finally {...} 代码块,不仅有大量的冗余代码,而且还影响代码的可读性。

使用统一异常处理

@ControllerAdvice 处理全局异常,可以指定不同的 ExceptionHandler 处理不同的异常。

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {/*** 业务异常* @param request* @param response* @param e* @return*/@ExceptionHandler(ServiceException.class)public Object businessExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e){log.error("[GlobalExceptionHandler][businessExceptionHandler] exception",e);JsonResult jsonResult = new JsonResult();jsonResult.setCode(JsonResultCode.FAILURE);jsonResult.setMessage("业务异常,请联系管理员");return jsonResult;}/*** 全局异常处理* @param request* @param response* @param e* @return*/@ExceptionHandler(Exception.class)public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e){log.error("[GlobalExceptionHandler][exceptionHandler] exception",e);JsonResult jsonResult = new JsonResult();jsonResult.setCode(JsonResultCode.FAILURE);jsonResult.setMessage("系统错误,请联系管理员");return jsonResult;}
}

使用 Assert 和Enum抛出异常

    @Testpublic void test1() {User user = userDao.selectById(userId);Assert.notNull(user, "用户不存在");}@Testpublic void test2() {User user = userDao.selectById(userId);if (user == null) {throw new userException("用户不存在.");}}

从上面的代码来看,使用 Assert 处理异常要优雅很多,但是这样做有个弊端,要定义很多自定义异常,也很麻烦。

我们可以使用 Assert 和枚举结合起来处理异常。

自定义断言
public interface BaseAssert {/*** 创建异常的接口,具体异常可由实现类来决定*/BaseException newException();/*** 创建异常的接口,具体异常可由实现类来决定,支持占位符参数列表*/BaseException newException(Object... args);/*** 断言 obj 非空。如果 obj 为空,则抛出异常*/default void isNotNull(Object obj) {if (obj == null) {throw newException();}}/*** 断言 obj 非空。如果 obj 为空,则抛出异常* 异常信息 message 支持传递参数方式,避免字符串拼接操作*/default void isNotNull(Object obj, Object... args) {if (obj == null) {throw newException(args);}}//更多类型自行定义}
自定义基础异常

它应该属于运行时异常,并且需要有错误码(code)、错误描述(message)等属性,满足这些条件应该就可以了。

@Getter
public class BaseException extends RuntimeException {// 错误码protected String code;// HTTP 状态码protected Integer http;private BaseException(String code, Integer http, String msg) {super(msg);this.code = code;this.http = http;}private BaseException(String code, Integer http, String msg, Throwable cause) {super(msg, cause);this.code = code;this.http = http;}public BaseException(ExceptionResponse resp) {this(resp.getCode(), resp.getHttp(), resp.getMessage());}public BaseException(ExceptionResponse resp, String message) {this(resp.getCode(), resp.getHttp(), message);}public BaseException(ExceptionResponse resp, String message, Throwable cause) {this(resp.getCode(), resp.getHttp(), message, cause);}
}
自定义业务异常

自定义业务异常都应该继承 BaseException 。

public class BusinessException extends BaseException {public BusinessException(ExceptionResponse resp) {super(resp);}public BusinessException(ExceptionResponse resp, String message) {super(resp, message);}
}

到目前为止已经实现了断言和自定义异常,但是此时我们并没有办法直接使用断言方法。

自定义断言
public interface BusinessExceptionAssert extends ExceptionResponse, BaseAssert {@Overridedefault BaseException newException() {return new BusinessException(this);}@Overridedefault BaseException newException(Object... args) {String msg = MessageFormat.format(this.getMessage(), args);return new BusinessException(this, msg);}
}
自定义返回实体
public interface ExceptionResponse {/*** 获取返回码* @return 返回码*/String getCode();/*** 返回 HTTP 状态码* @return*/Integer getHttp();/*** 获取返回信息* @return 返回信息*/String getMessage();
}
自定义枚举
public enum BusinessEnum implements BusinessExceptionAssert {USER_NOT_EXIST("10001", 400, "用户不存在"),;/*** 返回码*/private String code;/*** 状态码*/private Integer http;/*** 返回消息*/private String message;BusinessEnum(String code, Integer http, String message) {this.code = code;this.http = http;this.message = message;}@Overridepublic String getCode() {return code;}@Overridepublic String getMessage() {return message;}@Overridepublic Integer getHttp() {return http;}
}
自定义返回实体
@Data
public class BaseResponse<T> {private String code;private String message;private T data;}

Github星标90K,京东架构师一篇讲明白百亿级并发系统架构设计

全局异常处理
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {/*** 全局异常处理* @param request* @param response* @param e* @return*/@ExceptionHandler(BusinessException.class)public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, BusinessException e) {log.error("[GlobalExceptionHandler][exceptionHandler] exception",e);BaseResponse res = new BaseResponse();res.setCode(e.getCode());res.setMessage(e.getMessage());return res;}}
如何使用
    @RequestMapping(value="/queryById")public User queryById(Integer id) {User user = null;BusinessEnum.USER_NOT_EXIST.isNotNull(user);return user;}

总结

使用断言结合枚举的方式,灵活的实现了系统异常情况的判定,既不用定义大量的异常类,让代码可读性更高,以后只需要根据特定的异常情况定义枚举常量就可以了。

这篇关于别再写满屏的 try catch 了,教你如何统一处理异常!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/478700

相关文章

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

Go异常处理、泛型和文件操作实例代码

《Go异常处理、泛型和文件操作实例代码》Go语言的异常处理机制与传统的面向对象语言(如Java、C#)所使用的try-catch结构有所不同,它采用了自己独特的设计理念和方法,:本文主要介绍Go异... 目录一:异常处理常见的异常处理向上抛中断程序恢复程序二:泛型泛型函数泛型结构体泛型切片泛型 map三:文

Springboot3统一返回类设计全过程(从问题到实现)

《Springboot3统一返回类设计全过程(从问题到实现)》文章介绍了如何在SpringBoot3中设计一个统一返回类,以实现前后端接口返回格式的一致性,该类包含状态码、描述信息、业务数据和时间戳,... 目录Spring Boot 3 统一返回类设计:从问题到实现一、核心需求:统一返回类要解决什么问题?

maven异常Invalid bound statement(not found)的问题解决

《maven异常Invalidboundstatement(notfound)的问题解决》本文详细介绍了Maven项目中常见的Invalidboundstatement异常及其解决方案,文中通过... 目录Maven异常:Invalid bound statement (not found) 详解问题描述可

SpringSecurity中的跨域问题处理方案

《SpringSecurity中的跨域问题处理方案》本文介绍了跨域资源共享(CORS)技术在JavaEE开发中的应用,详细讲解了CORS的工作原理,包括简单请求和非简单请求的处理方式,本文结合实例代码... 目录1.什么是CORS2.简单请求3.非简单请求4.Spring跨域解决方案4.1.@CrossOr

requests处理token鉴权接口和jsonpath使用方式

《requests处理token鉴权接口和jsonpath使用方式》文章介绍了如何使用requests库进行token鉴权接口的处理,包括登录提取token并保存,还详述了如何使用jsonpath表达... 目录requests处理token鉴权接口和jsonpath使用json数据提取工具总结reques

Java Exception异常类的继承体系详解

《JavaException异常类的继承体系详解》Java中的异常处理机制分为异常(Exception)和错误(Error)两大类,异常分为编译时异常(CheckedException)和运行时异常... 目录1. 异常类的继承体系2. Error错误3. Exception异常3.1 编译时异常: Che

C# 空值处理运算符??、?. 及其它常用符号

《C#空值处理运算符??、?.及其它常用符号》本文主要介绍了C#空值处理运算符??、?.及其它常用符号,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录一、核心运算符:直接解决空值问题1.??空合并运算符2.?.空条件运算符二、辅助运算符:扩展空值处理

浅析Python中如何处理Socket超时

《浅析Python中如何处理Socket超时》在网络编程中,Socket是实现网络通信的基础,本文将深入探讨Python中如何处理Socket超时,并提供完整的代码示例和最佳实践,希望对大家有所帮助... 目录开篇引言核心要点逐一深入讲解每个要点1. 设置Socket超时2. 处理超时异常3. 使用sele

SpringMVC配置、映射与参数处理​入门案例详解

《SpringMVC配置、映射与参数处理​入门案例详解》文章介绍了SpringMVC框架的基本概念和使用方法,包括如何配置和编写Controller、设置请求映射规则、使用RestFul风格、获取请求... 目录1.SpringMVC概述2.入门案例①导入相关依赖②配置web.XML③配置SpringMVC