Sam*_*Sam 8 c# asp.net-mvc asp.net-web-api2
在我的Web API项目中,我创建了子项目(类库),我处理实际的数据处理操作.我的后端数据库是DocumentDB.
我的问题是如何告诉我的Web API操作方法我在类库中的数据方法中可能遇到的任何错误?一旦我的Web API方法知道错误,我就可以返回Http状态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
}
Run Code Online (Sandbox Code Playgroud)
---类库代码---
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?
}
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET Web API 2.1具有对未处理异常的全局处理的框架支持.
它允许用于自定义在发生未处理的应用程序异常时发送的HTTP响应.
因此,不要在类库中捕获异常.如果您需要在类库中记录异常,则将这些异常重新抛出到Presentation.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ...
config.Services.Replace(typeof (IExceptionHandler),
new GlobalExceptionHandler());
}
}
Run Code Online (Sandbox Code Playgroud)
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var exception = context.Exception;
var httpException = exception as HttpException;
if (httpException != null)
{
context.Result = new CustomErrorResult(context.Request,
(HttpStatusCode) httpException.GetHttpCode(),
httpException.Message);
return;
}
// Return HttpStatusCode for other types of exception.
context.Result = new CustomErrorResult(context.Request,
HttpStatusCode.InternalServerError,
exception.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
public class CustomErrorResult : IHttpActionResult
{
private readonly string _errorMessage;
private readonly HttpRequestMessage _requestMessage;
private readonly HttpStatusCode _statusCode;
public CustomErrorResult(HttpRequestMessage requestMessage,
HttpStatusCode statusCode, string errorMessage)
{
_requestMessage = requestMessage;
_statusCode = statusCode;
_errorMessage = errorMessage;
}
public Task<HttpResponseMessage> ExecuteAsync(
CancellationToken cancellationToken)
{
return Task.FromResult(_requestMessage.CreateErrorResponse(
_statusCode, _errorMessage));
}
}
Run Code Online (Sandbox Code Playgroud)
感谢ASP.NET Web API 2:从头到尾构建REST服务,以及源代码.
| 归档时间: |
|
| 查看次数: |
1672 次 |
| 最近记录: |