项目总结——异常

目的:

明确已知代码,错误范围,缩小排查问题难度。

 

异常:

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异常处理

 

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