抛出异常与日志记录 [英] Throw exception vs Logging

查看:322
本文介绍了抛出异常与日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是编写良好实践代码的方法吗?

Is the following way to code good practice?

try {
    //my code here
} catch (Exception e) {
    logger.error("Some error ", e);
    throw new MyCustomException("Some error ", e);
}

此外,我应该..

  • 仅使用记录器吗?
  • 仅抛出异常?
  • 两者都做吗?

我了解到,使用throw我可以在调用堆栈的另一部分捕获异常,但是附加日志记录可能具有一些隐藏的好处,并且也很有用.

I understand that with throw I can catch the exception in another part of the callstack, but maybe additional logging has some hidden benefits and is useful as well.

推荐答案

在某些情况下,我会同时使用日志记录和引发异常.特别是,它在API中很有用.通过抛出异常,我们可以允许调用方对其进行处理,并通过记录日志,我们可以自行确定其根本原因.

I use both in some cases, logging and throwing the exception. Specially, it's useful in APIs. By throwing the exception, we allow the caller to handle it, and by logging, we can identify the root cause of it ourself.

而且,如果调用者在同一系统中,那么如果我们在每个捕获中添加日志,则会有重复的日志.

And, if the caller is in the same system, then if we add logs in every catch, there will be duplicate logs.

这篇关于抛出异常与日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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