项目总结——异常
Posted 喵喵7781
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了项目总结——异常相关的知识,希望对你有一定的参考价值。
目的:
明确已知代码,错误范围,缩小排查问题难度。
异常:
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种类:
AnnotationFormatError, AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, FactoryConfigurationError, IOError,LinkageError, ServiceConfigurationError, ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError
虚拟机崩溃,IO错误等。
异常种类:
1.JDK定义异常,属于检查性异常(编译时不会被忽略)。
AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException,BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException,CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException,DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException,IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException,InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException,InvocationTargetException, IOException, JAXBException, JMException, KeySelectorException, LastOwnerException, LineUnavailableException,MarshalException, MidiUnavailableException, MimeTypeParseException, MimeTypeParseException, NamingException,NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException,ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException,RemarshalException, RuntimeException, SAXException, ScriptException, ServerNotActiveException, SOAPException, SQLException,TimeoutException, TooManyListenersException, TransformerException, TransformException, UnmodifiableClassException,UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException,URIReferenceException, URISyntaxException, UserException, XAException, XMLParseException, XMLSignatureException, XMLStreamException,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捕获,打印异常信息,返回用户异常信息和错误码。
参考资料:
以上是关于项目总结——异常的主要内容,如果未能解决你的问题,请参考以下文章