捕获特定异常而不是"Exception ex"



我正在将数据插入数据库,我想这里可能会出现某种异常,可能不止一个?

通常我曾经写过这样的东西:

try
{
//Execution code
}
catch(Exception ex)
{
// log error and throw it
}

我认为最好捕获一些特定的异常,而不是(Exception ex)这样的事情:

try
{
// my possibly bad code which inserts data to db
var someEntity = CreateEntityFromDTO(someDTO);
_context.SomeThing.Add(someEntity);
await _context.SaveChangesAsync(cancellationToken);
}
catch(MySpecificException mse)
{
// log error and throw it 
}

当涉及到在将数据插入数据库时捕获异常时,最佳实践是什么?

谢谢

干杯

你可以让你的SpecificExceptions从另一个更高级别DatabaseException继承,并在一个 catch 子句中处理所有Database Exceptions,例如

public class DatabaseException : Exception {}
public class MySpecificException : DatabaseException {}
public class YetAnotherDBSpecificException : DatabaseException {}
try
{
// insert data.
}
catch(DatabaseException dbEx)
{
// A database exception occured.
Console.Log(dbEx.Message);
}
catch(Exception other)
{
// Non db exception occured.
Console.Log(other.Message);
}

最新更新