import lombok.Data;
/**
* @author 01369526
*
*/
@Data
@SuppressWarnings("serial")
public class MyException extends RuntimeException implements Serializable{
private int errorcode;
public MyException(int errorcode,String message,Throwable throwable)
{
super(message,throwable);
this.errorcode=errorcode;
}}
import java.util.ArrayList;
import java.util.List;
/**
* @author 01369526
*
*/
public class Test {
public void test(int a)
{
if (a==0) {
try {
List list=new ArrayList<>();
list.add(666);
list.get(5);
} catch (Exception e) {
throw new MyException(666,"数组错误",e);
}}}
}
*/
public class Main {/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
new Test().test(0);
}
catch (MyException exception) {
// TODO: handle exception
System.out.println(exception.getErrorcode()+"\n"+exception.getMessage()+"\n");
exception.printStackTrace();
}
}}
输出:
666
数组错误MyException(errorcode=666)
at exception.Test.test(Test.java:20)
at exception.Main.main(Main.java:15)
Caused by: java.lang.IndexOutOfBoundsException: Index: 5, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at exception.Test.test(Test.java:17)
... 1 more
【java|java自定义异常类以及全局log打印】全局异常统一处理方法:
定义异常类统一设置值方法
/**
* 异常时设置result值工具类
* @author 01369526
*
*/
public class ExceptionSetUtil {
/**
*
* @param result
* @param code 错误代码
* @param message 错误消息
* @param logger 日志
* @param exception
*/
public static void setErrorCodeAndMessage(Result result,String code,String message,Logger logger,Throwable exception) {
logger.error(message,exception);
result.setErrorCode(code);
result.setErrorMessage(message);
}
}
自定异常类
import lombok.Data;
@Data
@SuppressWarnings("serial")
public class ZnfjRuntimeException extends RuntimeException{
String code;
public ZnfjRuntimeException(String code ,String message)
{
super(message);
this.code = code;
}public ZnfjRuntimeException(Throwable cause) {
super(cause);
}/**
* @Description:构造错误码,错误描述和错误堆栈
* @param code
* @param message
* @param cause
*/
public ZnfjRuntimeException(String code, String message, Throwable cause) {
super(cause instanceof ZnfjRuntimeException?cause.getMessage():message,cause);
if(cause instanceof ZnfjRuntimeException) {
this.code = ((ZnfjRuntimeException) cause).getCode();
}else {
this.code = code;
}
}public String getCode() {
return code;
}public void setCode(String code) {
this.code = code;
}
}
设置AOP
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sf.framework.domain.Result;
import dds.znfj.common.constant.ErrorCodeConstants;
import dds.znfj.common.exception.ZnfjRuntimeException;
import dds.znfj.common.utils.tdop.ExceptionSetUtil;
/**
* 统一日志处理类
*
* @author 01369526
*
*/
@Component
@Aspect
public class ServiceLogHandler {private static final Logger logger = LoggerFactory.getLogger(ServiceLogHandler.class);
/*@Around("execution(* com.sf.tdop.*.service.impl.*.*.*(..))")*//*第一个*代表所有的返回值类型,第二个*代表所有的包,第三个代表所有的类,第四个*代表类所有方法,最后一个..代表所有的参数。*/
//@Around("execution(* com.sf.dds.znfj.container.service.impl.*.*.*(..))||execution(* com.sf.dds.znfj.task.service.impl.*.*.*(..))")
//@Around("execution(* com.sf.dds.znfj.handover.service.impl.*.*.*(..))")
public Result> handleLog(ProceedingJoinPoint pjp) throws Throwable {
String name = pjp.getSignature().getName();
long startTime = System.currentTimeMillis();
logger.info("{}方法开始执行...", name);
Object[] args = pjp.getArgs();
for (Object obj : args) {
logger.debug("{}方法请求参数request:\n{\n{}\n}", name, obj);
}
Result> result = new Result<>();
try {
result = (Result>) pjp.proceed();
} catch (ZnfjRuntimeException e1) {
ExceptionSetUtil.setErrorCodeAndMessage(result, e1.getCode(), e1.getMessage(), logger, e1);
logger.error("error",e1);
return result;
}catch (Exception e) {
// TODO: handle exception
ExceptionSetUtil.setErrorCodeAndMessage(result,
ErrorCodeConstants.TdopCommonConstants.SYSTEM_ERROR_CODE,
ErrorCodeConstants.TdopCommonConstants.SYSTEM_ERROR_MESSAGE,
logger,
e);
logger.error("error",e);
return result;
}long endTime = System.currentTimeMillis();
float time = (endTime - startTime) / 1000.0f;
logger.info("{}方法执行结束,耗时{}s", name, time);
logger.debug(
"{}方法返回结果response:\n{\n\"requestId\":{},\n\"success\":{},\n\"business\":{},\n\"errorCode\":{},\n\"errorMessage\":{},\n\"date\":{},\n\"version\":{},\n\"obj\":{}\n}",
name, result.getRequestId(), result.isSuccess(), result.getBusiness(), result.getErrorCode(),
result.getErrorMessage(), result.getDate(), result.getVersion(), result.getObj());
return result;
}}
定义错误码:
public class ErrorCodeConstants {
private ErrorCodeConstants() {
}/**
* @Description: SQL_EXCEPTION sql异常
*/
public static final String SQL_EXCEPTION= "01";
/**
* @Description: IO_ERROR io异常
*/
public static final String IO_EXCEPTION= "02";
/**
* @Description: SYSTEM_ERROR system异常
*/
public static final String SYSTEM_EXCEPTION= "03";
/**
* @Description: SESSION_ERROR session异常
*/
public static final String SESSION_EXCEPTION= "04";
/**
* @Description: CUSTOMER_EXCEPTION 自定义异常
*/
public static final String CUSTOMER_EXCEPTION= "09";
/**
* @Description: DDS_ZNFJ_CORE_COMMON 公共基础模块
*/
public static final String DDS_ZNFJ_CORE_COMMON= "101";
/**/**
* @Description:公共基础模块
*/
public class TdopCommonConstants{
private TdopCommonConstants() {}public static final String INIT_SLICE_ERROR_CODE= DDS_ZNFJ_CORE_COMMON + SQL_EXCEPTION + "001";
public static final String INIT_SLICE_ERROR_MESSAGE= "初始化分片规则异常!";
public static final String SYSTEM_ERROR_CODE= DDS_ZNFJ_CORE_COMMON + SYSTEM_EXCEPTION + "001";
public static final String SYSTEM_ERROR_MESSAGE= "系统错误!";
}
最后加入扫描:
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)