尝试捕获以处理异常

时间:2018-06-26 16:41:26

标签: c# azure-cosmosdb

我正在尝试更新DocumentDb / CosmosDb中的某些文档,如果失败,则需要做其他事情,然后如果无法注销...

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

我不太确定,这似乎很笨拙..你们怎么看?

要获得额外的奖励积分,我需要经常这样做。.这样我可以在某个地方种田的事情会更好;)

3 个答案:

答案 0 :(得分:2)

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

因此,第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();

答案 1 :(得分:0)

为什么您对数据库的操作会失败?如果您希望采用不同的逻辑来处理结果,则最好为您知道并期望的条件进行编码,并做不同的事情。

Try catch将捕获所有内容,因此,如果您与数据库的连接失败等,或者您尝试读取或插入格式错误的数据等,则为

Try catch确实有各种例外情况,您可以进一步调查并捕获您感兴趣的特定例外情况。

try
   //try something
catch (Exception ex)            
{                
    if (ex is FormatException || ex is OverflowException)
    {
        //Do something specific;
        return;
    }

    throw;
}

答案 2 :(得分:0)

没关系,但是如果您说了一遍又一遍,最好提取该逻辑并重用它。
一种实现方法是拥有一个将first和section动作作为参数接受的方法,例如:

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)
相关问题