异常抛出判断处理笔记
自用的
异常处理类
@Slf4j
public class ExceptionUtilClass {
/**
* 异常抛出判断处理
* @param param
* @param msg
*/
public static void isVerify(Object param, String msg) {
/**
* 处理数据
* @param param
*/
try{
if (null == param) {
throw new ServiceException(msg);
}
if (param instanceof Boolean) {
if ((boolean) param) {
throw new ServiceException(msg);
}
}
if (param instanceof List<?>) {
if (((List<?>) param).isEmpty()) {
throw new ServiceException(msg);
}
}
if (param instanceof Integer) {
if ((Integer) param < 1) {
throw new ServiceException(msg);
}
}
if (param instanceof String) {
if ( StringUtils.isBlank((String)param)) {
throw new CustomException(msg);
}
}
}catch (ServiceException v){
log.info("自定义异常:{}", v.getMessage());
throw new ServiceException(v.getMessage());
}catch (Exception e){
log.info("系统未知异常:{}", e.getMessage());
throw new ServiceException(e.getMessage());
}finally {
log.info("自定义异常处理完成");
}
}
}
异常类
public class ServiceException extends RuntimeException{
public ServiceException() {
}
public ServiceException(String message) {
super(message);
}
}
调用
verifyCodeDto(需要判断的异常参数)
ExceptionUtil.isVerify(verifyCodeDto, "抛出异常信息");
如:
ExceptionUtil.isVerify(verifyCodeDto, "授权码或设备类型为空");
ExceptionUtil.isVerify(verifyCodeDto.getAuthCode(), "授权码为空");
ExceptionUtil.isVerify(verifyCodeDto.getManagementType(), "设备类型为空");
ExceptionUtil.isVerify(eqEquipment.getStatus() != 0, "设备已到期或已禁用");
异常详细信息的获取
/**
* 获取exception的详细错误信息。
*/
public static String getExceptionMessage(Throwable e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
return str;
}
public static String getRootErrorMseeage(Exception e)
{
Throwable root = ExceptionUtils.getRootCause(e);
root = (root == null ? e : root);
if (root == null)
{
return "";
}
String msg = root.getMessage();
if (msg == null)
{
return "null";
}
return StringUtils.defaultString(msg);
}