【发布时间】:2015-01-24 02:08:26
【问题描述】:
在我的 Web API 项目中,我创建了处理实际数据处理操作的子项目(类库)。我的后端数据库是 DocumentDB。
我的问题是如何告诉我的 Web API 操作方法我在类库的数据方法中可能遇到的任何错误?一旦我的 Web API 方法知道错误,我就可以返回 Http status 500 或类似的东西,但我不确定在 catch 部分应该有什么(见下文)以及如何通知调用 Web API 方法遇到的错误?
--- Web API 方法---
public async Task<IHttpActionResult> DoSomething(Employee emp)
{
var employeeRecord = await MyClassLibrary.DoSomethingWithEmployee(emp);
// Here, I want to check for errors
}
--- 类库代码---
public static async Task<Employee> DoSomethingWithEmployee(Employee emp)
{
try
{
// Logic here to call DocumentDB and create employee document
}
catch
{
// This is where I catch the error but how do I notify the calling Web API method that there was an error?
}
}
【问题讨论】:
-
你可以让异常冒出来。请注意,您的代码应尽可能避免异常。例外应该是真正例外的事情,例如数据库不可用。
-
@sam 我不会担心检查 DoSomething 中的 数据库异常 或 类库异常。理想情况下,您不想在操作方法中处理每个异常。相反,让 GlobalExceptionHandler 处理这些错误。您可以在开源 MVC 项目中看到这种方法。 (见下面我的回答)
标签: c# asp.net-mvc asp.net-web-api2