奥德提出了一个很好的观点。
我认为可以在本主题中添加的是对 API 的抽象。您需要创建一个异常包装器,为所有实现提供通用合同。我知道它已被 oded 的响应所涵盖,但我认为可以指出:
void Main()
{
try
{
IUserRepository = //assume that IoC container provides specific implementation
}
catch (UserNotFoundException e)
{
Console.WriteLine(string.Format("User not found: {0}", e.Id));
}
}
class User
{
public int Id {get;set;}
}
class UserNotFoundException : Exception
{
public int Id {get;private set;}
public UserNotFoundException(int id, Exception innerException)
:base(string.Format("User {0} could not be found", id), innerException)
{
Id = id;
}
}
interface IUserRepository
{
User GetUser(int id);
}
class XmlUserRepository : IUserRepository
{
string _path;
public XmlUserRepository(string path)
{
_path = path;
}
public User GetUser(int id)
{
try
{
//retrieving code that might throw IOException or XmlException
}
catch (Exception e)
{
//catching Exception is not a good thing to do, but for the sake of clarity I made this like that
throw new UserNotFoundException(id, e);
}
}
}
class DbUserRepository : IUserRepository
{
string _dbConnectionString;
public DbUserRepository(string dbConnectionString)
{
_dbConnectionString = dbConnectionString;
}
public User GetUser(int id)
{
try
{
//retrieving code that might throw SqlException
}
catch (Exception e)
{
//catching Exception is not a good thing to do, but for the sake of clarity I made this like that
throw new UserNotFoundException(id, e);
}
}
}