Web API中的异常处理 [英] Exception handling in Web API

查看:321
本文介绍了Web API中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web API项目中,我创建了用于处理实际数据处理操作的子项目(类库).我的后端数据库是DocumentDB.

In my Web API project, I created sub projects (class libraries) where I handle actual data handling operations. My backend database is DocumentDB.

我的问题是,如何将类库中数据方法中可能遇到的任何错误告知Web API操作方法?一旦我的Web API方法知道该错误,我就可以返回Http status 500或类似的信息,但是我不确定在catch部分应该有什么(见下文)以及如何通知调用Web API方法遇到错误?

My question is how do I tell my Web API action methods of any errors I may encounter within data methods in my class libraries? Once my Web API method knows about the error, I can just return Http status 500 or something like that but I'm not sure what I should have in the catch part (see below) and how I can notify the calling Web API method of the error encountered?

--- Web API方法---

--- Web API Method ---

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?
   }
}

推荐答案

ASP.NET Web API 2.1具有对未处理异常的全局处理的框架支持.

ASP.NET Web API 2.1 have framework support for global handling of unhandled exceptions.

它允许使用自定义发生未处理的应用程序异常时发送的HTTP响应.

It allows use to customize the HTTP response that is sent when an unhandled application exception occurs.

因此,不要在类库中捕获异常.如果需要将异常记录在类库中,则将这些异常重新抛出到Presentation中.

So, do not catch exception in Class Library. If you are required to log exception in Class Library, then re-throw those exception to Presentation.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // ...

        config.Services.Replace(typeof (IExceptionHandler), 
            new GlobalExceptionHandler());
    }
}

GlobalExceptionHandler

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);
    }
}

CustomErrorResult

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));
    }
}

贷方 ASP.NET Web API 2 :从头到尾构建REST服务,并源代码.

这篇关于Web API中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆