日志对象(CustomException)实例化的Java注释?

日志对象(CustomException)实例化的Java注释?,java,Java,关于对象实例化和日志记录的Java小问题 在我们的(太大的)项目中,我们有一个特殊的异常MyCustomException,它被抛出 通常的代码如下所示: if (conditionNotMet()) { throw new MyCustomException(); if (conditionNotMet()) { LOGGER.error(something bad happened, throwing a new MyCustomException()); thro

关于对象实例化和日志记录的Java小问题

在我们的(太大的)项目中,我们有一个特殊的异常MyCustomException,它被抛出

通常的代码如下所示:

if (conditionNotMet()) {
    throw new MyCustomException();
if (conditionNotMet()) {
    LOGGER.error(something bad happened, throwing a new MyCustomException());
    throw new MyCustomException();
@LogMeWhenIamCreated
public MyCustomException(...) {
   
这种类型的投掷有好几千次。 对于所有这些,我们希望添加日志记录,例如:

if (conditionNotMet()) {
    throw new MyCustomException();
if (conditionNotMet()) {
    LOGGER.error(something bad happened, throwing a new MyCustomException());
    throw new MyCustomException();
@LogMeWhenIamCreated
public MyCustomException(...) {
   
正如您所能想象的,由于我们有成千上万的日志记录程序,我们正在浪费大量时间在所有地方添加日志记录程序

我想知道,我们是否可以在MyCustomException上添加某种注释,例如:

if (conditionNotMet()) {
    throw new MyCustomException();
if (conditionNotMet()) {
    LOGGER.error(something bad happened, throwing a new MyCustomException());
    throw new MyCustomException();
@LogMeWhenIamCreated
public MyCustomException(...) {
   
这样我们就可以把这个注释放在一个地方,并且仍然能够看到我们想要的日志,而不必遍历整个代码库和数千次抛出


谢谢

我在这里看到三个选项:

  • 使用AOP处理创建
    MyCustomException
    。按照下面的步骤,查看如何编写类创建的方面。还可以在创建注释时为
    @logmewheniam添加注释
  • 使用regex查找所有
    抛出新的MyCustomException()构造并在抛出之前添加日志记录。缺点是显而易见的——变化很多
  • 按照Rohan的建议,将日志记录添加到
    MyCustomException
    构造函数中

  • 选项1和2的缺点是:如果您在某些地方构造了异常,但没有抛出异常,则仍会添加日志消息。

    在创建新的MyCustomException时,即在此类的构造函数中,您不能进行日志记录吗?