【问题标题】:Either log or rethrow this exception记录或重新抛出此异常
【发布时间】:2015-11-18 18:19:46
【问题描述】:

Sonar complaining about logging and rethrowing the exception 可能重复。

这是我在课堂上的代码:

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());
    }

还有我的 Logger 类:

    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 指向catch (final Exception e) 并说Either log or rethrow this exception。你怎么看?

【问题讨论】:

    标签: java android sonarqube code-analysis sonar-runner


    【解决方案1】:

    如果你看一下规则RSPEC-1166的描述,尤其是标题:

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

    在您的情况下,您只处理异常的 消息,因此不保留原始 异常(包括其 stacktrace .因此,您生成的日志将隐藏失败的根本原因。

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

    适当的修复

    这可能不适合您的情况:

    • 要么将规则标记为“不会修复”
    • 或停用质量配置文件中的规则

    【讨论】:

    • 感谢您的信息,但我仍然感到困惑。如果您查看Noncompliant code example,第二个样本,try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); } 看起来像我的。不是吗?
    • 是的,这被认为是_NON_compliant,所以这不是预期的吗?
    • 是的,谢谢。我为花时间在这上面而头疼……你说得对。
    • 带有链接和修复的优秀解释,值得期待改进的编辑。我只是answered related question with RSPEC-2139也许你喜欢“改善回来”?️
    猜你喜欢
    • 2017-01-17
    • 2015-10-26
    • 2022-01-12
    • 2012-02-21
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多