能告诉我IExceptionhandler的优点和缺点吗?

时间:2014-03-04 05:49:43

标签: asp.net-web-api

任何人都能告诉我web api中使用的IExceptionhandler的优点和缺点吗? 哪一个是在Web Api中处理异常的最佳方法?

在我的下面示例中,我使用IExceptionHandler来处理所有的web api异常。 在HandleCore方法中,我正在处理Httpexceptions,MyCustomerrormessages,Unhandled Exceptions。 任何人都可以告诉我,处理IExceptionHandler的HandleCore方法中的所有异常是正确的方法吗?

命名空间AccessServices.EntityModel {

/// <summary>
/// To Handle the unhandled exceptions caught by Web API. 
/// </summary>
public class CustomExceptionHandler : IExceptionHandler
{
    public virtual Task HandleAsync(ExceptionHandlerContext context,
                                    CancellationToken cancellationToken)
    {
        if (!ShouldHandle(context))
        {
            return Task.FromResult(0);
        }

        return HandleAsyncCore(context, cancellationToken);
    }

    public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
                                        CancellationToken cancellationToken)
    {
        HandleCore(context);
        return Task.FromResult(0);
    }

    public virtual void HandleCore(ExceptionHandlerContext context)
    {
    }

    public virtual bool ShouldHandle(ExceptionHandlerContext context)
    {
        return context.ExceptionContext.CatchBlock.IsTopLevel;
    }

}

/// <summary>
///Response to unhandled exceptions caught by Web API.
/// </summary>
public class OopsExceptionHandler : CustomExceptionHandler
{
    public override void HandleCore(ExceptionHandlerContext context)
    {
        var exception = context.Exception;

        if (exception is HttpException)
          {
             var httpException = (HttpException)exception;
              context.Result = new TextPlainErrorResult
              {
                  Request = context.ExceptionContext.Request,
                  Content = exception.Message,
                  Statuscode=(HttpStatusCode)httpException.GetHttpCode()
              };

          }
        else if (exception is MyCustomException)
        {

         context.Result = new TextPlainErrorResult
            {
                //Request = context.ExceptionContext.Request,
                Content = MyCustomException.Message,
                Statuscode = MyCustomException.StatusCode
            };

        }

          else
          {
            context.Result = new TextPlainErrorResult
                                   {
                                       Request = context.ExceptionContext.Request,
                                       Content = "Oops! Sorry! Something went wrong." +
                                                 "Please contact Administrator",
                                        Statuscode=HttpStatusCode.InternalServerError
                                   };
          }
    }
    /// <summary>
    /// Sends HttpResponseMessage to the client
    /// </summary>
    private class TextPlainErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }
        public string Content { get; set; }
        public HttpStatusCode Statuscode { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage(Statuscode)

                               {
                                  Content = new StringContent(Content),
                                  RequestMessage = Request
                               };
           return Task.FromResult(response);
        }
    }
}

}

1 个答案:

答案 0 :(得分:2)

IExceptionHandler的目的是为Web API中发生的未处理异常提供全局错误处理机制。

ExceptionFilterAttributes只能处理来自Web API某些区域的异常...例如,如果从身份验证过滤器,授权过滤器,操作过滤器和动作。

如果抛出异常,例如,从MessageHandlers,路由匹配或写出响应,则不会调用异常过滤器,因为它们位于分层堆栈中的高位。因此,全局错误处理功能(IExceptionLoggerIExceptionHandler)尝试在所有层中提供一致的体验。