代码之家  ›  专栏  ›  技术社区  ›  m1nkeh

尝试catch处理异常[关闭]

  •  1
  • m1nkeh  · 技术社区  · 6 年前

    我正在尝试更新documentdb/cosmossdb中的一些文档,如果失败,需要做其他事情,然后如果失败,则将其注销…

    try { 
        do a thing w/ database
    }
    catch (DocumentClientException dce1) {
        try {
            do another, alternative thing w/ database
        }
        catch (DocumentClientException dce2) {
            log to app insights.
        }
    }
    

    我不确定这件事,它看起来很笨重。你们觉得怎么样?

    对于额外的奖励积分,我需要经常这样做。所以我能在某个地方耕种的东西会更好;)

    3 回复  |  直到 6 年前
        1
  •  2
  •   John Wu    6 年前

    我个人会避免将异常流与功能逻辑流混合在一起。它会变脆。相反,将异常转换为逻辑标志,并在普通逻辑构造中使用它。

    因此,步骤1捕获异常并基于它设置一个变量或返回值,并将其包装为一个独立的方法,以掩盖来自其他人的混乱:

    bool TryDoSomethingWithDataBase()
    {
        try
        {
            //Do thing that could fail
            return true;
        }
        catch(SpecificException ex)
        {
            return false;
        }
    }
    
    bool TryDoSomethingElseWithDataBase()
    {
        try
        {
            //Do thing that could fail
            return true;
        }
        catch(SpecificException ex)
        {
            return false;
        }
    }
    

    第2步是像往常一样编写逻辑:

    if (!TryDoSomethingWithDatabase())
    {
        if (!TryDoSomethingElseWithDatabase())
        {
            LogFatalError();
        }
    }
    

    var ok = TryDoSomethingWithDatabase();
    if (ok) return;
    ok = TryDoSomethingElseWithDatabase();
    if (ok) return;
    LogFatalError();
    
        2
  •  0
  •   Fuzzybear    6 年前

    为什么数据库会失败?如果您想进入一个不同的逻辑来处理结果,那么最好对您所知道和期望的条件进行编码,并做不同的事情。

    Try Catch将捕获任何内容,因此,如果您与数据库的连接失败等,或者如果您试图读取或插入格式错误的数据等。

    Try-Catch确实有各种异常,您可以进一步调查并捕获您感兴趣的特定异常。例如

    try
       //try something
    catch (Exception ex)            
    {                
        if (ex is FormatException || ex is OverflowException)
        {
            //Do something specific;
            return;
        }
    
        throw;
    }
    
        3
  •  0
  •   Ido Ran    6 年前

    这是可以的,但是如果你说你会一次又一次的拥有它,那么最好提取这个逻辑并重用它。
    实现这一点的一种方法是使用一个方法,将第一个动作和部分动作作为参数,例如:

    public void TryThis(Action doFirst, Action doSecond)
    {
      try { 
          doFirst();
      }
      catch (DocumentClientException dce1) {
          try {
              doSecond();
          }
          catch (DocumentClientException dce2) {
              log to app insights.
          }
      }
    }
    

    然后像这样使用:

    public void DoSomethig1()
    {
    ...
    }
    
    public void DoSomething2()
    {
    ...
    }
    
    TryThis(DoSomething1, DoSomething2)