软件开发过程中,不可避免的是需要处理各种异常,如何优雅的抛出异常

自定义一个 异常基类继承运行时异常类 RuntimeException 让其他自定义异常继承
import lombok.Data;
/**
*
* 自定义一个 异常基类继承运行时异常类
* 让其他自定义异常继承
* @author not_simple
* @version 1.0
* @date 2020/8/17 20:50
*/
@Data
public class BaseException extends RuntimeException{
private int code;
private String message;
public BaseException(){
}
public BaseException(int code ,String message){
this.code = code;
this.message = message;
}
public BaseException(IResponseEnum responseEnum,Object[] args){
this.code = responseEnum.getCode();
this.message = responseEnum.getMessage();
}
public BaseException(IResponseEnum responseEnum,Object[] args, Throwable cause){
this.code = responseEnum.getCode();
this.message = responseEnum.getMessage();
}
}
自定义业务异常 继承BaseException
让ExceptionHandler能够捕获到抛出的是 BusinessException 自定义业务异常
/**
*
* 自定义业务异常 继承BaseException
* 让ExceptionHandler能够捕获到抛出的是 BusinessException 自定义业务异常
*
* @author not_simple
* @version 1.0
* @date 2020/8/18 18:46
*/
public class BusinessException extends BaseException {
private static final long serialVersionUID = 1L;
public BusinessException(int code ,String message) {
super(code,message);
}
public BusinessException(IResponseEnum responseEnum, Object[] args) {
super(responseEnum, args);
}
public BusinessException(IResponseEnum responseEnum, Object[] args, Throwable cause) {
super(responseEnum, args, cause);
}
}
枚举接口 必须存在 getCode 和getMessage方法
/**
*
* 枚举接口 必须存在 getCode 和getMessage方法
*
* @author not_simple
* @version 1.0
* @date 2020/8/17 20:52
*/
public interface IResponseEnum {
int getCode();
String getMessage();
}
Assert 断言接口 子类实现newException方法
assertNotNull 如果对象为空抛出异常 调用newException方法 而实现接口的子类需要实现newException方法 返回值类型就是抛出异常的类型
/**
* @author not_simple
* @version 1.0
* @date 2020/8/14 8:41
*
* Assert 断言接口 子类实现n

本文介绍了在软件开发中如何使用Springboot优雅地处理异常。通过定义枚举接口包含getCode和getMessage方法,以及使用Assert断言接口,实现自定义异常的newException方法。此外,还展示了如何通过ResponseEnum实现BusinessExceptionAssert接口,达到全局异常处理、全局数据绑定和全局数据预处理的效果。未定义的异常情况也给出了解决方案,并提供了源代码链接。
最低0.47元/天 解锁文章
2245

被折叠的 条评论
为什么被折叠?



