如何在 ASP.net web-api 中使用自定义异常处理程序

How to use customexceptionhandlers in ASP.net web-api

我正在尝试了解自定义异常处理程序,但没有掌握它的窍门。我尝试实现自定义异常处理程序,如下页所述:
https://www.exceptionnotfound.net/the-asp-net-web-api-exception-handling-pipeline-a-guided-tour/ https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling

现在我的代码是:

public class CustomRestErrorHandlerException : ExceptionHandler
{
    public void CustomError(String error)
    {
        var message = new HttpResponseMessage(HttpStatusCode.NoContent)
        {
            Content = new StringContent("An unknown error occurred saying" + error)
        };

        throw new HttpResponseException(message);
    }

    public override void Handle(ExceptionHandlerContext context)
    {
        if (context.Exception is ArgumentNullException)
        {
            var result = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "ArgumentNullException"
            };

            context.Result = new ErrorMessageResult(context.Request, result);
        }
        else if (context.Exception is ArgumentException)
        {
            var result = new HttpResponseMessage(HttpStatusCode.NoContent)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Argument is not found"
            };

            context.Result = new ErrorMessageResult(context.Request, result);
        }
        else if (context.Exception is ArgumentOutOfRangeException)
        {
            var result = new HttpResponseMessage(HttpStatusCode.NotImplemented)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Argument is out of range"
            };

            context.Result = new ErrorMessageResult(context.Request, result);

        }
        else
        {
            CustomError(context.Exception.Message);
        }
    }

    public class ErrorMessageResult : IHttpActionResult
    {
        private HttpRequestMessage _request;
        private HttpResponseMessage _httpResponseMessage;

        public ErrorMessageResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
        {
            _request = request;
            _httpResponseMessage = httpResponseMessage;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(_httpResponseMessage);
        }
    }
}

然后我尝试调用我显然做错的异常处理程序:(这个我可能不明白<<

    [Route("api/***/***")]
    [HttpGet]
    public IHttpActionResult Clear****()
    {
        try
        {
            // try clearing
        }
        catch(Exception e)
        {
            throw new CustomRestErrorHandlerException();     << error occurs here 
        }

        return this.Ok();
    }

如您所见,发生错误是因为异常不是异常处理程序,但我不知道如何通过自定义异常处理程序抛出异常,因为它没有任何解释。

谁能用一个小例子向我解释一下?

引用自:https://www.exceptionnotfound.net/the-asp-net-web-api-exception-handling-pipeline-a-guided-tour/:

"The handler, like the logger, must be registered in the Web API configuration. Note that we can only have one Exception Handler per application."

config.Services.Replace(typeof(IExceptionHandler), new CustomRestErrorHandlerException ()); 

所以将上面的行添加到 WebApiConfig.cs 文件中,然后简单地从控制器中抛出一个异常:

[Route("api/***/***")]
[HttpGet]
public IHttpActionResult Clear****()
{
    // do not use try catch here
    //try
    //{
        // try clearing
    //}
    //catch(Exception e)
    //{
        //throw new CustomRestErrorHandlerException();     << error occurs here 
    //}

    throw new Exception();
}

ExceptionHandler 必须在 Web API 配置中注册。这可以在 WebApiConfig.cs 文件中完成,如下所示,其中配置的类型为 System.Web.Http.HttpConfiguration.

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

一旦它们被注册,它们就会在未处理的异常期间被自动调用。要对其进行测试,您可能需要在操作方法中抛出异常,例如:

[Route("api/***/***")]
[HttpGet]
public IHttpActionResult Clear****()
{
    try
    {
        // try clearing
    }
    catch(Exception e)
    {
        throw new ArgumentNullException();     << error occurs here 
    }

    return this.Ok();
}

您现在可以在异常处理程序中放置一个断点,并查看全局异常处理程序如何捕获未处理的异常。