java自定义异常类以及全局log打印
2017-10-16 19:42
351 查看
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<Integer> 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
全局异常统一处理方法:
定义异常类统一设置值方法
/** * 异常时设置result值工具类 * @author 01369526 * */ public class ExceptionSetUtil { /** * * @param result * @param code 错误代码 * @param message 错误消息 * @param logger 日志 * @param exception */ public static <T> void setErrorCodeAndMessage(Result<T> 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 = "系统错误!"; }
最后加入扫描:
<context:component-scan base-package="dds.znfj" />
相关文章推荐
- java自定义异常以及异常的使用
- java中异常抛出以及自定义异常
- Think in Java 笔记_Chapter12_1_Exception基础_异常处理3_自定义异常以及抛出多个异常的处理
- 【慕课笔记】第一章 异常与异常处理 第4节 JAVA中的异常抛出以及自定义异常
- 详解Java的内置异常以及创建自定义异常子类的方法
- Java如何自定义异常打印非堆栈信息详解
- Android中全局异常捕获以及动态logcat打印。方便上线项目分析
- 深入java 自定义异常以及常用
- java自定义异常以及throws和throw的区别
- java自定义异常以及异常类
- java基础16 捕获、抛出以、自定义异常和 finally 块(以及关键字:throw 、throws)
- Java继承Exception自定义异常类教程以及Javaweb中用Filter拦截并处理异常
- Java 实现自定义异常 以及如何使用该异常
- ASP.NET全局错误处理和异常日志记录以及IIS配置自定义错误页面
- 黑马程序员 Java基础 处理异常信息以及自定义异常
- java异常解析以及自定义异常实例
- java常见异常笔试题以及自定义异常
- Android c/c++层打印log信息和java层打印log信息
- Java自定义异常类
- java-自定义异常操作