简体   繁体   English

如何从 Stacktrace 隐藏一个方法,但不隐藏它的异常?

[英]How to hide a method from Stacktrace but not its exception?

I am facing this situation where I have my method which throws some exception.我正面临这种情况,我的方法会引发一些异常。 I mask the exception so that it is not shown what exactly is, however in the stack trace the method it comes from is also shown.我屏蔽了异常,因此它没有显示到底是什么,但是在堆栈跟踪中也显示了它来自的方法。

The code is something like this:代码是这样的:

public Something methodForHiding() throws Exception {
    try { 
            some code
       }
    catch (Exception e) {
       throw ExcpetionMask.maskExep();
   }
   return Something
}

In the stacktrace I get:在堆栈跟踪中,我得到:

at com.Program.maskedException
at com.Program.methodForHiding

I would like to remove this methodForHiding from the stacktrace and leave only the maskedException我想从堆栈跟踪中删除这个methodForHiding并只留下maskedException

Is there any way to achieve this?有什么办法可以做到这一点?

You can do it as follows:你可以这样做:

public class CustomException extends Exception{

    public CustomException() {
        StackTraceElement[] stackTrace = super.getStackTrace();
        StackTraceElement[] newArray = Arrays.stream(stackTrace).filter(i -> i.getMethodName().equals("The method to remove"))
                .toArray(StackTraceElement[]::new);
        super.setStackTrace(newArray);
    }
}

On the constructor of your custom exception edit the stack trace by calling public void setStackTrace(StackTraceElement[] stackTrace) .在自定义异常的构造函数上,通过调用public void setStackTrace(StackTraceElement[] stackTrace)来编辑堆栈跟踪。

First get the currently stack trace using public StackTraceElement[] getStackTrace() , then filter the method that you do not want to be shown in the stack, and set the new stack trace accordingly.首先使用public StackTraceElement[] getStackTrace()获取当前堆栈跟踪,然后过滤您不希望在堆栈中显示的方法,并相应地设置新的堆栈跟踪。

Personally, I think it would be better to instead of removing the method simply replace its name by something like就个人而言,我认为最好不要删除该方法,而是简单地将其名称替换为类似

"Method removed from call stack" “从调用堆栈中删除的方法”

to not mislead those that have to look at the stack trace to find out the source a bug.不要误导那些必须查看堆栈跟踪以找出错误来源的人。

You can do this with Throwable.setStackTrace .您可以使用Throwable.setStackTrace执行此操作。 Just pass in an array with the relevant element omitted.只需传入一个省略相关元素的数组即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM