等于方法不能很好地与可抛掷一起使用



我有一些外部提供的回调要运行。由于它们可以包含任何内容,因此我宁愿冒险捕获它们Throwable,因此从任何可恢复的错误中恢复。

允许回调执行的某些阶段引发错误,除非错误连续重复两次。在这种情况下,它们将被标记为无效,除非用户手动启动它们,否则无法再运行。

这是旨在处理的方法:

  /**
   * Sets whether the bot is disabled due to error or not. If error has occured during 
   * getWindow, the bot will be disabled immediatelly. If the error occured during canRun() or run()
   * the bot will only be disabled if the error is repetitive.
   * @param error error that occured
   * @param phase phase of execution in which the error occured
   * @return true if this error is not significant enough to cancel this bot
   */
  public boolean continueOnError(Throwable error, ExecutionPhase phase) {
    System.err.println("Error "+error+" caught in robot "+this.getClass().getName());
    System.err.println("Last: "+lastError+((error.equals(lastError)?" which is the same as last":" which is defferent than last")));
    if(phase == ExecutionPhase.GET_WINDOW || (error.equals(lastError) && phase==errorPhase)) {
      //Remember last
      setLastError(error, phase);
      //If robot state listener is listening, inform it about this event
      if(listener!=null)
        listener.disabledByError(error);
      //Disable the robot - on attempt to run, it will throw RobotDisabledException
      return !(errorDisabled = true);
    }
    //Rememeber last
    setLastError(error, phase);
    //The robot can remain running, but next same error will turn it down
    return true;
  }

我知道这是一种原始的方法,但我需要从某个地方开始。此代码的问题在于 Throwable allways 上的 equals 方法返回 false。查看此方法生成的输出:

Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last

为什么会这样?

Throwable不会覆盖Objectequals,所以error.equals(lastError)的行为与error == lastError相同。

也许这对您比较类就足够了:

error.getClass().equals(lastError.getClass())

Throwable不会覆盖equals(),存在问题 您的ErrorLastError实例可能是 2 个不同的Throwable具有相同值的实例

equals()不起作用,因为它只比较实例。如果你抛出"相同"的异常两次,那会给你两个实例,Object.equals()为此返回 false。

在Java中没有完美的方法来检查两个异常是否相同(例如,它们可能包含时间戳)。

更好的方法可能是记住导致问题的组件,并在它开始抛出太多错误(无论是哪个错误或它们是否重复)时禁用它。

此外,Throwable捕获您可能不想要的不可恢复Error。代码应该适用于Exception甚至RuntimeException,具体取决于您的设计的工作方式。

相关内容

最新更新