在 Web API 中,可以使用 ExceptionHandler 来处理异常并返回适当的错误响应。以下是一种优雅的方式来使用 ExceptionHandler:

  1. 创建一个自定义的异常类,继承自 Exception 类。例如:
public class CustomException : Exception
{
    public CustomException(string message) : base(message)
    {
    }
}
  1. 创建一个全局异常过滤器,实现 IExceptionFilter 接口。在该过滤器中,可以使用 ExceptionHandler 来捕获并处理异常。例如:
public class GlobalExceptionHandler : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        if (context.Exception is CustomException)
        {
            // 处理自定义异常
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = 'Custom Exception'
            };

            context.ExceptionHandled = true;
            context.Result = new ResponseMessageResult(response);
        }
        else
        {
            // 处理其他异常
            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent('An error occurred.'),
                ReasonPhrase = 'Internal Server Error'
            };

            context.ExceptionHandled = true;
            context.Result = new ResponseMessageResult(response);
        }
    }
}
  1. 在 WebApiConfig.cs 中注册全局异常过滤器。例如:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // 注册全局异常过滤器
        config.Filters.Add(new GlobalExceptionHandler());

        // 其他配置...
    }
}

通过以上步骤,可以在 Web API 中优雅地使用 ExceptionHandler 来处理异常并返回适当的错误响应。使用自定义的异常类可以更好地组织和管理不同类型的异常,同时全局异常过滤器可以统一处理异常并返回一致的错误响应。

Web API 中优雅的异常处理:使用 ExceptionHandler

原文地址: https://www.cveoy.top/t/topic/qrlF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录