为什么是“记录并抛出"?被认为是反模式? [英] Why is "log and throw" considered an anti-pattern?

查看:39
本文介绍了为什么是“记录并抛出"?被认为是反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是由围绕 这篇文章,我没有收到任何好的答案.

This question was sparked by a discussion around this article, where I did not receive any good answers.

如果您不能以其他方式处理它,为什么要记录您的异常然后重新抛出它(当然保留原始堆栈跟踪)是一个坏主意?

推荐答案

我认为答案主要是因为如果你不能处理它,你为什么要抓住它?如果他们觉得它值得记录,为什么不让任何可以处理它的人(或者除了处理它别无选择的人)记录它?

I assume the answer is largely because why are you catching it if you can't handle it? Why not let whomever can handle it (or whomever is left with no choice but to handle it) log it, if they feel that it is log-worthy?

如果您捕获并记录并重新抛出它,那么上游代码就无法知道您已经记录了异常,因此同一个异常可能会被记录两次.或者更糟糕的是,如果所有上游代码都遵循相同的模式,则异常可能会被记录任意次数,对于决定捕获它的代码中的每个级别一次,记录它,然后再次抛出它.

If you catch it and log it and rethrow it, then there's no way for the upstream code to know that you've already logged the exception, and so the same exception might get logged twice. Or worse, if all the upstream code follows this same pattern, the exception might be logged an arbitrary number of times, once for each level in the code that decides to catch it, log it, and then throw it again.

还有一些人可能会争辩说,由于抛出和捕获异常是相对昂贵的操作,所有这些捕获和重新抛出都无助于您的运行时性能.它也不会在简洁性或可维护性方面帮助您的代码.

Also some might argue that since throwing and catching exceptions are relatively costly operations, all this catching and rethrowing isn't helping your runtime performance. Nor is it helping your code in terms of conciseness or maintainability.

这篇关于为什么是“记录并抛出"?被认为是反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆