gpt4 book ai didi

java - 如何在java中的每个catch block 之前注入(inject)日志语句

转载 作者:行者123 更新时间:2023-11-30 03:23:14 25 4
gpt4 key购买 nike

我最初使用 JBoss 进行面向方面编程,并实现了代码注入(inject) - 调用方法之前和之后以及方法抛出异常之后。现在我想知道我们如何在方法中注入(inject)代码?我想在每个 catch block 执行之前注入(inject)一个 Logging 语句,我们如何使用 java 来做到这一点?

最佳答案

我对 JBoss AOP 不太了解,但无论如何您都可以使用 AspectJ,因为它具有 handler() 切入点。

驱动程序应用程序:

package de.scrum_master.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

import javax.naming.NamingException;

public class Application {
public static void throwRandomException() throws TimeoutException, IOException, NamingException {
switch (new Random().nextInt(5)) {
case 0: throw new TimeoutException("too late, baby");
case 1: throw new FileNotFoundException("file.txt");
case 2: throw new IOException("no read permission");
case 3: throw new NullPointerException("cannot call method on non-existent object");
case 4: throw new NamingException("unknown name");
}
}

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
try { throwRandomException(); }
catch (NullPointerException e) {}
catch (FileNotFoundException e) {}
catch (TimeoutException e) {}
catch (IOException e) {}
catch (NamingException e) {}
}
}
}

方面:

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class CaughtExceptionLogger {
@Before("handler(*) && args(e)")
public void logCaughtException(JoinPoint thisJoinPoint, Exception e) {
System.out.println(thisJoinPoint + " -> " + e.getMessage());
}
}

控制台输出:

handler(catch(TimeoutException)) -> too late, baby
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(NamingException)) -> unknown name
handler(catch(TimeoutException)) -> too late, baby
handler(catch(NamingException)) -> unknown name
handler(catch(NamingException)) -> unknown name
handler(catch(NullPointerException)) -> cannot call method on non-existent object
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(NullPointerException)) -> cannot call method on non-existent object

关于java - 如何在java中的每个catch block 之前注入(inject)日志语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com