如何从异常处理程序获取方法内字段的值
我有一个执行多个命令的代码,我需要跟踪步骤 根据步骤号跟踪失败
如何从异常处理程序获取方法内的字段值 我不想使用 try/catch 子句。
也许可以用 Aspect J 在测试方法上写注释?
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
@Test
public void runCode(){
Integer test = 0;
System.out.println(test);
test = 1;
System.out.println(test);
if(true) throw new RuntimeException(" error thrown");
test = 2;
System.out.println(test);
}
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public void handleValidationException(RuntimeException throwable) {
//TODO how to get here the last step
System.out.println("failed as step: ");
}
}
只是为了澄清我的代码并没有真正抛出异常 我可能会在读取文件、写入文件等时遇到异常。 因此,对于意外的异常,我怎样才能完成最后一步
I have a code that executes multiples commands, I need to track the steps
to track failures based on the step number
How to get a value of a field inside a method from exception handler
I don't want to use try/catch clause.
Maybe it's possible to write it annotation on the test Method with Aspect J?
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
@Test
public void runCode(){
Integer test = 0;
System.out.println(test);
test = 1;
System.out.println(test);
if(true) throw new RuntimeException(" error thrown");
test = 2;
System.out.println(test);
}
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public void handleValidationException(RuntimeException throwable) {
//TODO how to get here the last step
System.out.println("failed as step: ");
}
}
Just to clarify My code not really throwing an exception
I might get an exception from reading a file, writing a file etc..
So for unexpected an Exception how can i get the last step
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当抛出异常时,局部变量的值将丢失。没有办法让他们回来。
跟踪它们的唯一方法是在引发异常之前保护它们。这可能如下所示 - 基于 Johannes Kuhn 对 Bohemian 的答案的评论的建议以及该答案:
应该添加一些错误处理......
当然,您可以创建自己的异常类,派生自
RuntimeException
,它将test
的值作为其构造函数的附加参数,也许还加上一些可能对您诊断故障有用的附加信息,并将其放入catch
阻止。是的,通常你不应该捕获
Throwable
。但这条规则适用于生产代码,不适用于测试用例。The values of the local variables are lost, when an exception is thrown. No way to get them back.
The only way to track them is to secure them before the exception is thrown. This may look like below – based on the suggestion from Johannes Kuhn's comment to the answer from Bohemian and that answer:
Some error handling should be added …
Of course you can create your own exception class, derived from
RuntimeException
, that takes the value oftest
as an additional argument for its constructor, perhaps plus some additional information that might be useful for your diagnosis of the failure, and throw that in thecatch
block.And yes, usually you should never catch
Throwable
. But this rule is for production code, not for test cases.捕获并将
test
添加到异常消息中:然后在 catch 中检查它:
Catch and add
test
to the exception message:Then inspect it in the catch: