項目總結——異常

目的:

明確已知代碼,錯誤範圍,縮小排查問題難度。

 

異常:

What is Throwable?

The {@code Throwable} class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java {@code throw} statement. Similarly, only this class or one of its subclasses can be the argument type in a {@code catch} clause.

Throwable是所有errors的子類和exceptions的子類在java語言中的超類(父類)。只有對象instances of這個類(或者它的子類們)纔可以由Java虛擬機拋出異常,或者通過throw進行拋出。同理,只有這個類或它的子類可以是{@code catch}子句中的參數類型。

類及其子類是 Throwable 的一種形式,它指出了合理的應用程序想要捕獲的條件。

異常

Error種類:

AnnotationFormatErrorAssertionErrorAWTErrorCoderMalfunctionErrorFactoryConfigurationErrorFactoryConfigurationErrorIOError,LinkageErrorServiceConfigurationErrorThreadDeathTransformerFactoryConfigurationErrorVirtualMachineError

虛擬機崩潰,IO錯誤等。

 

異常種類:

1.JDK定義異常,屬於檢查性異常(編譯時不會被忽略)。

AclNotFoundExceptionActivationExceptionAlreadyBoundExceptionApplicationExceptionAWTExceptionBackingStoreException,BadAttributeValueExpExceptionBadBinaryOpValueExpExceptionBadLocationExceptionBadStringOperationExceptionBrokenBarrierException,CertificateExceptionClassNotFoundExceptionCloneNotSupportedExceptionDataFormatExceptionDatatypeConfigurationException,DestroyFailedExceptionExecutionExceptionExpandVetoExceptionFontFormatExceptionGeneralSecurityExceptionGSSException,IllegalAccessExceptionIllegalClassFormatExceptionInstantiationExceptionInterruptedExceptionIntrospectionException,InvalidApplicationExceptionInvalidMidiDataExceptionInvalidPreferencesFormatExceptionInvalidTargetObjectTypeException,InvocationTargetExceptionIOExceptionJAXBExceptionJMExceptionKeySelectorExceptionLastOwnerExceptionLineUnavailableException,MarshalExceptionMidiUnavailableExceptionMimeTypeParseExceptionMimeTypeParseExceptionNamingException,NoninvertibleTransformExceptionNoSuchFieldExceptionNoSuchMethodExceptionNotBoundExceptionNotOwnerExceptionParseException,ParserConfigurationExceptionPrinterExceptionPrintExceptionPrivilegedActionExceptionPropertyVetoExceptionRefreshFailedException,RemarshalExceptionRuntimeExceptionSAXExceptionScriptExceptionServerNotActiveExceptionSOAPExceptionSQLException,TimeoutExceptionTooManyListenersExceptionTransformerExceptionTransformExceptionUnmodifiableClassException,UnsupportedAudioFileExceptionUnsupportedCallbackExceptionUnsupportedFlavorExceptionUnsupportedLookAndFeelException,URIReferenceExceptionURISyntaxExceptionUserExceptionXAExceptionXMLParseExceptionXMLSignatureExceptionXMLStreamException,XPathException

2.自定義異常,屬於運行時異常(編譯時可能會被忽略,跟隨業務的進行和參數的變化,會throw Exception)。

根據業務場景定義的異常,異常觸發動作跟業務緊密聯繫。

常見樣例(自定義異常):

public class CoreException extends RuntimeException{
	
    private static final long serialVersionUID = 1L;
    
    private int errorCode = -1;

    public CoreException(String errMsg){
        super(errMsg);
    }

    public CoreException(String errMsg, int errorCode){
        super(errMsg);
        this.errorCode = errorCode;
    }

    /**
     * 通過枚舉類來構造異常
     * @param coreResponseEnum
     */
    public CoreException(CoreResponseEnum coreResponseEnum){
        super(coreResponseEnum.getMessage());
        this.errorCode = coreResponseEnum.getCode();
    }
    
    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}

常見樣例(Aop異常):

maven pom :

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.2</version>
</dependency>
package com.wm.aspect;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.wm.CoreResponseDto;
import com.wm.CoreExceptionEnum;
import com.wm.CoreException;

/**
 * @ClassName:ExceptionInterceptorAspect.java
 * @Description: 異常攔截器切面
 */
@Aspect
@Component("coreExceptionInterceptorAspect")
@Order(0)
public class ExceptionInterceptorAspect {

	private static final Logger logger = LoggerFactory.getLogger(ExceptionInterceptorAspect.class);

	@Pointcut("execution(* com.wm.*.*(..))")
	public void exceptionInterceptor(){

	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Around(value = "exceptionInterceptor()")
	public Object interceptException(ProceedingJoinPoint pjp) {
		Method method = ((MethodSignature) pjp.getSignature()).getMethod();
		try {
			return pjp.proceed();
		} catch (Throwable e) {
			//如果是手動拋出的自定義異常
			if (e instanceof CoreException) {
				logger.error("[aop] method ->{}, args ->{},  throw CoreException ->{}", method.getName(),
						JSON.toJSONString(pjp.getArgs()), e.getMessage());
				int code = ((CoreException) e).getErrorCode();
				return new CoreResponseDto(code!=0 ? code : CoreResponseDto.FAILURE, e.getMessage(), null);
			//如果是手動拋出的普通異常
			} else {
				logger.error("[aop] method ->{}, args ->{},  throw exception ->{}", method.getName(),
						JSON.toJSONString(pjp.getArgs()), getErrorInfoFromException(e));
				return new CoreResponseDto(CoreResponseDto.FAILURE,
						CoreExceptionEnum.COMMON_EXCEPTION.getName(), null);
			}
		}
	}

	public static String getErrorInfoFromException(Throwable e) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "\r\n" + sw.toString() + "\r\n";
		} catch (Exception e2) {
			return e.getMessage();
		}
	}
}

 

應用場景:

異常常結合try catch , 日誌一起使用。一般對外接口不能直接暴露異常信息給業務方,需要try catch核心流程。如果有異常,則被catch捕獲,打印異常信息,返回用戶異常信息和錯誤碼。

 

 

參考資料:

java異常處理

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章