java 记录或重新抛出此异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32197329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:48:18  来源:igfitidea点击:

Either log or rethrow this exception

javaandroidsonarqubecode-analysissonar-runner

提问by Hesam

Possible duplicate of Sonar complaining about logging and rethrowing the exception.

可能重复的声纳抱怨记录和重新抛出异常

This is my code in a class:

这是我在课堂上的代码:

try
    {
        this.processDeepLinkData(data);
    }
    catch (final Exception e)
    {
        // Error while parsing data
        // Nothing we can do
        Logger.error(TAG, "Exception thrown on processDeepLinkData. Msg: " + e.getMessage());
    }

and my Logger class:

和我的记录器类:

    import android.content.Context;
    import android.util.Log;
    import com.crashlytics.android.Crashlytics;

    public final class Logger
    {
        /**
         * Convenience method.
         *
         * @see Logger#log(String, String)
         */
        public static void error(final String tag, final String msg)
        {
            if (Logger.DEBUG)
            {
                Log.e(tag, "" + msg);
            }
            else
            {
                Logger.log(tag, "" + msg);
            }
        }

        private static void log(final String tag, final String msg)
        {
            Crashlytics.log(tag + ": " + msg);
        }
}

Sonar is pointing to catch (final Exception e)and says Either log or rethrow this exception. What do you think?

声纳指着catch (final Exception e)Either log or rethrow this exception。你怎么认为?

回答by benzonico

If you look at the rule description : https://rules.sonarsource.com/java/RSPEC-1166

如果您查看规则说明:https: //rules.sonarsource.com/java/RSPEC-1166

And especially the title :

尤其是标题:

Exception handlers should preserve the original exception

异常处理程序应保留原始异常

In your case you are only taking care of the message of the exception, thus not preserving the eventual stacktrace (and so the root cause of the failure).

在您的情况下,您只处理异常消息,因此不会保留最终的堆栈跟踪(以及失败的根本原因)。

This rule detects that you are not using the caught exception as an entire object in the catch block.

此规则检测到您没有将捕获的异常用作 catch 块中的整个对象。

This might not be suitable in your case : either mark the rule as "won't fix" or deactivate it in your quality profile.

这可能不适合您的情况:将规则标记为“无法修复”或在您的质量配置文件中停用它。