一、自定义异常
import lombok.extern.slf4j.Slf4j; import java.util.Map; @Slf4j public class SysException extends RuntimeException { private ExceptionCodeEnum code; private String msg; private String path; private Map<String, Object> params; public SysException(ExceptionCodeEnum type) { this.code = type; } public SysException(ExceptionCodeEnum code, String msg) { super(msg); this.code = code; this.msg = msg; log.error("自定义异常,code : " + code + " msg : " + msg); } public ExceptionCodeEnum getCode() { return code; } public SysException setCode(ExceptionCodeEnum code) { this.code = code; return this; } public String getMsg() { return msg; } public SysException setMsg(String msg) { this.msg = msg; return this; } public String getPath() { return path; } public SysException setPath(String path) { this.path = path; return this; } public Map<String, Object> getParams() { return params; } }
二、异常类型
public enum ExceptionCodeEnum { /** * */ SUCCESS("000", "成功"), /** * */ ERROR_ALARM_ENTITY("011", "失败,告警无法匹配告警源实体"), /** * */ ERROR_ALARM_INFO("021", "失败,处理状态信息无法匹配原告警信息"), /** * */ USER_OR_PASS_ERROR("997", "账户密码校验失败"), /** * */ XML_EXCEPTION("998", "解释XML出异常"), /** * 其它原因 */ ERROR_DATA("-1","参数列表错误(缺少,格式不匹配)"), /** * 其它原因 */ ERROR_REASONS("999", "其它原因"), ; private final String code; private final String msg; ExceptionCodeEnum(String code, String msg) { this.code = code; this.msg = msg; } public String code() { return code; } public String msg() { return msg; } }
三、异常触发
try{ if (异常触发条件) { larm.setAlarmType("0"); }else{ throw new SysException(ExceptionCodeEnum.ERROR_REASONS, "接口不存在"); } } catch (SysException e) { msg = errorAlarmEntity(getXml(resultEntity), e, e.getCode(), msgBody); e.printStackTrace(); }