前言
BusinessException(业务异常类),使用场景:程序并未出现执行异常情况,人为抛出异常信息。例如:登录功能,账号不存在或者密码错误时,可抛出一个业务异常,自定义异常信息。
业务异常类创建
其中ResError为错误枚举类。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.saas.reptile.common.result.ResError;
import lombok.Data;
/**
* @author sed
* @ClassName: BusinessException
* @Description: 业务异常类, 使用场景:程序并未出现执行异常情况,人为抛出异常信息。
* 例如:登录功能,账号不存在或密码错误时,可抛出一个业务异常,自定义异常信息
* @date 2021-08-31
*/
@Data
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 1L;
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* 异常对应的返回码
*/
private Integer code;
/**
* 异常对应的描述信息
*/
private String message;
private Throwable throwable;
public BusinessException() {
super();
}
public BusinessException(String message) {
super(message);
this.message = message;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
this.message = message;
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
this.message = String.format("%s %s", message, cause.getMessage());
}
public BusinessException(int code, String message, Throwable throwable) {
super(message);
this.code = code;
this.message = message;
this.throwable = throwable;
}
public BusinessException(ResError resError) {
this(resError.getCode(), resError.getMessage(), null);
}
public BusinessException(ResError resError, Throwable throwable) {
this(resError.getCode(), resError.getMessage(), throwable);
}
public BusinessException(ResError resError, Object... args) {
super(resError.getMessage());
String message = resError.getMessage();
try {
message =
String.format("%s %s", resError.getMessage(), OBJECT_MAPPER.writeValueAsString(args));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
this.message = message;
this.code = resError.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
使用场景
控制层
@ApiOperation(value = "修改菜单")
@RequestMapping(value = "/updateMenu", method = RequestMethod.PUT)
public Result updateMenu(@RequestBody Menu menu) {
Result result = new Result();
try {
menuService.updateByPrimaryKey( menu );
} catch (BusinessException b) {
result.setCode( ResultCodeEnum.SYSTEMERROR.getCode(), b.getMessage() );
} catch (Exception e) {
result.setCode( ResultCodeEnum.SYSTEMERROR.getCode(), ResultCodeEnum.SYSTEMERROR.getName() );
logger.error( "修改菜单:", e );
}
return result;
}
service层
@Override
@Logs(title = "修改菜单", code = "menu")
public void updateByPrimaryKey(Menu menu) {
if ( menu.getIconCode() != null && menu.getIconCode().length() > 50) {
throw new BusinessException( "长度不能超过50" );
} else {
menuMapper.updateByPrimaryKey( menu );
}
}
dao层:略