java自定義異常類的編寫,[轉載] java自定義異常類以及全局log打印

 2023-11-19 阅读 29 评论 0

摘要:參考鏈接: 用Java打印異常消息的3種不同方式 import lombok.Data; ? /** java自定義異常類的編寫??* @author 01369526 ?* ?*/ @Data @SuppressWarnings("serial") java獲取異常信息,public class MyException extends RuntimeException impleme

參考鏈接: 用Java打印異常消息的3種不同方式

import lombok.Data;

?

/**

java自定義異常類的編寫??* @author 01369526

?*

?*/

@Data

@SuppressWarnings("serial")

java獲取異常信息,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;

java獲取全局變量、import java.util.List;

?

/**

?* @author 01369526

?*

java全局異常捕捉??*/

public class Test {

public void test(int a)

{

? ? if (a==0) {

java 自定義異常類,? ? ? ? try {

? ? ? ? ? ? List<Integer> list=new ArrayList<>();

? ? ? ? ? ? list.add(666);

? ? ? ? ? ? list.get(5);

?

全局靜態變量。? ? ? ? } catch (Exception e) {

? ? ? ? ? ? throw new MyException(666,"數組錯誤",e);

? ? ? ? }

?

? ? }}

java定義全局常量,}?

?*/

public class Main {

?

? ? /**

java打印異常信息。? ? ?* @param args

? ? ?*/

? ? public static void main(String[] args) {

? ? ? ? // TODO Auto-generated method stub

? ? ? ? try {

java全局常量,? ? ? ? ? ? new Test().test(0);

? ? ? ? }

? ? ? ? catch (MyException exception) {

? ? ? ? ? ? // TODO: handle exception

? ? ? ? ? ? System.out.println(exception.getErrorcode()+"\n"+exception.getMessage()+"\n");

java如何拋出自定義異常,? ? ? ? ? ? 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" />

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/181252.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息