【问题标题】:How to throw an error with transaction java如何使用事务 java 引发错误
【发布时间】:2018-06-01 06:22:03
【问题描述】:

我正在做这样的事情:

try {
            client.restoreFromClusterSnapshot(req);
        } catch (AmazonRedshiftException e) {
            txUtils.execute((ts) -> {
                redshiftDto.setStatus(ResourceStatus.FAILED);
                redshiftDto.setStatusDetails(e.getMessage());
                redshiftDto.setUpdatedOn(Timestamp.from(Instant.now()));
                this.rdao.merge(redshiftDto);
                return null;
            });
            LOGGER.error("CANNOT START REDSHIFT- " + e.getErrorMessage());
            throw new AmazonRedshiftException( "CANNOT START REDSHIFT- "
              + e.getErrorMessage());

        }

在这段代码中,如果我抛出错误,我将无法设置数据库变量,因为它正在终止我的事务。如果我评论 throw 它将起作用并且我的数据库值将被设置。但我不能扔任何东西。我怎么能同时做-(在数据库中抛出和设置值)

【问题讨论】:

  • 这可能是由于txUtils 对您抛出的异常做出反应,抛出txUtils 无法处理的异常。另外,请指定txUtils属于哪个类。
  • 为什么你必须在那里执行那个事务,而不是在你处理异常的地方?
  • 尝试调试代码,这将帮助您检查 txUtils 实际在做什么,控制是否回到您的代码行“throw new AmazonRedshiftException...”??
  • 我正在执行该事务,因为如果 restoreFromClusterSnapshot 失败,那么它应该将 FAILED 设置为 db 中的红移状态,我将能够通过抛出它在 UI 中将其显示为 Failed 我会让 UI 显示错误

标签: java exception exception-handling


【解决方案1】:

我要做的是使用finally 子句。

AmazonRedshiftException exception = null;
try {
    cluster = client.restoreFromClusterSnapshot(req);
} catch (AmazonRedshiftException e) {
    exception = e;
    LOGGER.error("CANNOT START REDSHIFT- " + e.getErrorMessage());
    throw new AmazonRedshiftException( "CANNOT START REDSHIFT- "
          + e.getErrorMessage());
} finally {
    if(exception != null) {
        txUtils.execute((ts) -> {
            redshiftDto.setStatus(ResourceStatus.FAILED);
            redshiftDto.setStatusDetails(exception.getMessage());
            redshiftDto.setUpdatedOn(Timestamp.from(Instant.now()));
            this.rdao.merge(redshiftDto);
            return null;
        });
    }
}

【讨论】:

  • 这个可以用。但是初始化 AmazonRedshiftException 然后使用它,行越来越多。我们可以使用像制作 BaseException 类然后抛出它的东西吗
猜你喜欢
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
相关资源
最近更新 更多