为什么是“登陆和抛出”隐藏反格局? [英] Why is "log and throw" condsidered an anti-pattern?

查看:231
本文介绍了为什么是“登陆和抛出”隐藏反格局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

为什么要记录你的异常,然后重新抛出它(当然保留原始的堆栈跟踪)是一个坏主意,否则不能处理? / em>

Why should logging your exception and then rethrowing it (preserving the original stack trace of course) be a bad idea if you can't handle it otherwise?

推荐答案

我认为答案很大程度上是因为如果你无法处理它,你为什么要抓住它?为什么不让任何人处理它(或任何人不得不处理它)登录,如果他们觉得这是日志值得的?

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天全站免登陆