项目中需要在后端将报错返回给前端,通过抛异常的方式能减少重复代码量
使用spring的@ExceptionHandler(BizException.class)捕捉代码中抛出的BizException异常
BizException类
import com.titian.sqb.core.common.utils.i18n.I18nUtils;
public class BizException extends RuntimeException {
private String code;
private Object[] args;
public BizException(String code) {
this.code = code;
}
public BizException(String code, Object... args) {
this.code = code;
this.args = args;
}
public BizException(String code,String message, Object... args) {
super(message);
this.code = code;
this.args = args;
}
public BizException(Throwable e, String code) {
super(I18nUtils.message(code), e);
}
public BizException(Throwable e, String code, String... args) {
super(I18nUtils.message(code, args), e);
}
@Override
public String getMessage() {
return super.getMessage();
}
public String getCode() {
return this.code;
}
public Object[] getArgs() {
return this.args;
}
}
捕捉异常,这边根据需要返回就好
@ExceptionHandler(BizException.class)
public Result bizException(BizException e) {
if (e.getMessage()!=null){
return Result.error(e.getCode(),e.getMessage(),e.getArgs());
}
return Result.error(e.getCode(), e.getArgs());
}
然后在需要返回报错信息的业务逻辑中抛出异常
throw new BizException("Err", "这里是错误信息");
扩展一下,也可以将判空等处理做成工具类
例如:
public static void isNull(Object object, String message) {
if (object == null) {
throw new BizException(message);
}
}
这样代码看起来更舒服
BizException.isNull(null, "报错信息")