当前位置:网站首页>Unified exception reporting practice based on bytecode
Unified exception reporting practice based on bytecode
2022-06-29 12:07:00 【InfoQ】
Unified exception reporting practice based on bytecode
One 、 Preface
Two 、 Exception introduction
2.1 Understanding anomalies
- What's going on ?
- Who will handle exceptions ?
- How to handle exceptions ?
2.2 Java Classification of exceptions

2.3 Exception handling process

2.4 Principles of exception throwing and catching
- Unnecessary use of exceptions
- Throw an exception using a descriptive message
- Exceptions within your ability must be handled
- Exceptions should be ignored with reason
2.5 know try/catch/finally
- The code execution process has not entered try Code block .
- Code in try Life and death cycle in code block 、 Deadlock, etc .
- stay try In the code block System.exit() operation .
3、 ... and 、 exception handling
3.1 Best practices for handling exceptions
- When you need to throw an exception up , Exceptions with business meaning need to be defined according to the current business scenario , Give priority to exceptions defined within the industry or defined within the team . For example, in use dubbo Throw when the remote service call times out DubboTimeoutException, Instead of putting RuntimeException Throw out .
- Please do not leave finally Used in code blocks return sentence , Avoid complicated judgment of return value .
- Catch exception specific subclasses , instead of Exception, Not to mention throwable. This will catch all the errors , Include JVM A fatal error thrown that cannot be handled .
- Don't neglect any abnormality (catch I don't do anything about it ), Even now, we can make sure that it doesn't affect the normal operation of the logic , But no one can guarantee how the code will change in the future , Don't dig a hole for yourself .
- Don't use exceptions as control processes , This is a very strange and influential practice .
- Cleaning up resources , Release connections and other operations must be placed in finally Block of code , Prevent memory leaks , If finally Block processing has more logic and modularity , We can encapsulate tool method calls , The code will be simpler .
3.2 Turn to the practice of abnormal monitoring and reporting
public String doSomething(String arg) {
try {
return method1(arg);
} catch (Exception e) {
log.error("call method1 error msg={}", e.getMessage());
// do Alarm related logic
} finally {
// do close resource
}
return null;
}
ASMJavassistByteCode
premain3.3 ASM+javaAgent Realize unified reporting of abnormal information
public static void premain(String arg, Instrumentation inst) {
LOG.info("******** AgentApplication.premain executing, String Param: {}********", arg);
inst.addTransformer(new CustomClassFileTransformer(), true);
LOG.info("******** AgentApplication premain executed ********");
}
@Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
// Determine whether the current class needs to be enhanced
if (!needEnhance(className)) {
return classfileBuffer;
}
try {
ClassReader cr = new ClassReader(className);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
CustomClassVisitor classVisitor = new CustomClassVisitor(cw);
cr.accept(classVisitor, ClassReader.EXPAND_FRAMES);
return cw.toByteArray();
} catch (IOException e) {
LOG.warn("desc=CustomClassFileTransformer.transform, className:{} Exception:{}", className, e);
}
return classfileBuffer;
}
@Override
public MethodVisitor visitMethod(int access, String methodName, String desc, String signature, String[] exceptions) {
MethodVisitor mv = cv.visitMethod(access, methodName, desc, signature, exceptions);
// Skip ignored methods , Such as the construction method <init>, toString etc.
if (!SKIP_METHODS.contains(methodName) && mv != null) {
mv = new CustomMethodVisitor(mv, className, methodName);
}
return mv;
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
exceptionHandlers.add(handler);
super.visitTryCatchBlock(start, end, handler, type);
}
@Override
public void visitLineNumber(int line, Label start) {
if (exceptionHandlers.contains(start)) {
ExceptionProcessor.injectHandleLogic(this, className, methodName, line);
}
super.visitLineNumber(line, start);
}
/**
* Injection processing logic
* Call exception handling methods {@link ExceptionProcessor#process(Throwable, String, String, int)}
*
* @param visitor Method visitor
* @param className Class name
* @param methodName Method name
* @param lineNumber catch It starts with the block Line number ( There may be more than one in a method catch block , Index Introduction lineNumber, Identify abnormal position with accurate marker )
*/
public static void injectHandleLogic(MethodVisitor visitor, String className, String methodName, int lineNumber) {
visitor.visitInsn(DUP);
visitor.visitLdcInsn(className);
visitor.visitLdcInsn(methodName);
visitor.visitLdcInsn(lineNumber);
visitor.visitMethodInsn(INVOKESTATIC, EXCEPTION_HANDLE_CLASS, EXCEPTION_HANDLE_METHOD, EXCEPTION_HANDLE_PARAM, false);
}
/**
* Logic for handling exceptions
* In this method, we can clearly know the class throwing exceptions 、 Method 、 Line number and other abnormal information , Easy to assemble and report information, convenient for R & D positioning
* Please do not modify the method signature {@link ExceptionProcessor#injectHandleLogic(MethodVisitor, String, String, int)} Call in
*
* @param exception Exception to handle
* @param className Class name
* @param methodName Method name
* @param lineNumber catch The line number at the beginning of the block
* @param <T> Abnormal paradigm
*/
public static <T extends Throwable> void process(T exception, String className, String methodName, int lineNumber) {
try {
className = className.replace(File.separator, ".");
String itemName = generateItemNameAfterFilter(exception.getClass().getSimpleName(), className, methodName);
if (StringUtil.isEmpty(itemName)) {
return;
}
// Alarm logic processing
ZzMonitor.sumWithAlarm(itemName, 1, String.valueOf(lineNumber), true);
} catch (RuntimeException e) {
LOG.error("desc=ExceptionProcessor.process error", e);
}
}
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<!-- Modify the full path of your own class name -->
<Premain-Class>com.****.AgentApplication</Premain-Class>
<Can-Retransform-Classes>true</Can-Retransform-Classes>
<Can-Redefine-Classes>true</Can-Redefine-Classes>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
-javaagent:./lib/auto-monitor-alarm-1.0.0.jar

Four 、 summary
JavaAgentASMReference resources
Author's brief introduction
边栏推荐
- Jerry's about TWS channel configuration [chapter]
- Information technology application and innovation professionals (database) intermediate training hot enrollment (July 6-10)
- Follow Me Study HCIE-Big Data-Data Mining 第一章 数据挖掘介绍 模块一
- & 3 view request message and response message in browser
- 小白学习MySQL - 增量统计SQL的需求 - 开窗函数的方案
- RSLO:自监督激光雷达里程计(实时+高精度,ICRA2022)
- Numpy的ndarray数组基础
- Pro test! Centos7 deploy PHP + spool
- 请问股票开户收费吗 网上开户安全吗?
- PyTorch学习之归一化层(BatchNorm、LayerNorm、InstanceNorm、GroupNorm)[通俗易懂]
猜你喜欢

How to view saved passwords of websites

MMdet的Resnet卷积替换成Ghost卷积组所出现的问题

Win11 web version

镜像漏洞扫描工具:Trivy

Pytorch - 分布式通信原语(附源码)

Embedded database development programming (IV) -- DDL, DML

Jericho's position on initiating the connection back to the opposite ear: 【 chapter 】

跟着官方学电机,BLDC两种控制策略,学到即赚到

自动化测试摸索之路---准备工作

TTChat x Zadig 开源共创 Helm 接入场景,环境治理搞得定!
随机推荐
什么是外链和内链?
Jericho's position on initiating the connection back to the opposite ear: 【 chapter 】
&4 express框架
Jerry's configuration of TWS cross pairing [chapter]
镜像漏洞扫描工具:Trivy
torch. Load load model error: can't get attribute 'VAE_ vc‘ on <module ‘__ main__‘ From 'xxxx() run file path‘
杰理之关于开机发起回连对耳的位置:【篇】
自动化测试摸索之路---准备工作
深入理解 volatile 关键字
ETL为什么经常变成ELT甚至LET?
正大期货主账户留4行情软件用的什么?
现在怎么开户?有没有更快又安全的开通渠道
Follow Me Study HCIE-Big Data-Data Mining 第一章 数据挖掘介绍 模块一
Jerry's WiFi interferes with Bluetooth [chapter]
Safety innovation practice | Haitai Fangyuan was invited to participate in the technical exchange Seminar on "network information innovation and value co creation in the digital age"
大家有没有觉得学机械的人很可怕?
QT learning 15 separation of user interface and business logic
TTChat x Zadig 开源共创 Helm 接入场景,环境治理搞得定!
[VTK] MFC grid editor based on vtk8.2
[graduation season] summarize the past and look forward to the future