c# webapi如何處理異常

c#
小樊
81
2024-09-28 05:08:02

在C# Web API中處理異常有多種方法,以下是一些建議:

  1. 使用全局異常處理器:在Web API應(yīng)用程序中,可以使用全局異常處理器來(lái)捕獲和處理所有未處理的異常。要實(shí)現(xiàn)這一點(diǎn),請(qǐng)?jiān)贕lobal.asax文件中添加以下代碼:
using System.Web.Http;
using System.Web.Routing;
using System.Web.Mvc;

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        HttpException httpException = exception as HttpException;
        if (httpException != null)
        {
            // 處理HTTP異常,例如404、500等
            Response.Clear();
            Server.ClearError();
            Response.StatusCode = httpException.GetHttpCode();
            Response.StatusDescription = httpException.GetStatusDescription();
            // 可以在這里添加自定義的錯(cuò)誤處理邏輯,例如記錄日志、發(fā)送通知等
        }
        else
        {
            // 處理其他類(lèi)型的異常
            Response.Clear();
            Server.ClearError();
            Response.StatusCode = 500;
            Response.StatusDescription = "Internal Server Error";
            // 可以在這里添加自定義的錯(cuò)誤處理邏輯,例如記錄日志、發(fā)送通知等
        }

        // 返回一個(gè)錯(cuò)誤響應(yīng)
        IHttpActionResult errorResponse = new JsonResult(new
        {
            Code = (int)Response.StatusCode,
            Message = Response.StatusDescription
        });

        Response.Content = JsonConvert.SerializeObject(errorResponse);
    }
}
  1. 在控制器中處理異常:在控制器中,可以使用try-catch語(yǔ)句來(lái)捕獲和處理異常。例如:
public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        try
        {
            // 你的業(yè)務(wù)邏輯代碼
        }
        catch (Exception ex)
        {
            // 處理異常,例如記錄日志、發(fā)送通知等
            return InternalServerError(ex.Message);
        }

        return Ok("Success");
    }
}
  1. 使用過(guò)濾器處理異常:在Web API中,可以使用過(guò)濾器(Filter)來(lái)處理異常。例如,可以創(chuàng)建一個(gè)自定義的異常過(guò)濾器,如下所示:
using System.Web.Http;
using System.Web.Mvc;

public class CustomExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        // 處理異常,例如記錄日志、發(fā)送通知等
        HttpException httpException = filterContext.Exception as HttpException;
        if (httpException != null)
        {
            filterContext.Result = new HttpStatusCodeResult(httpException.GetHttpCode(), httpException.GetStatusDescription());
        }
        else
        {
            filterContext.Result = new HttpStatusCodeResult(500, "Internal Server Error");
        }
    }
}

然后,在控制器或API配置中應(yīng)用此過(guò)濾器:

[CustomExceptionFilter]
public class MyController : ApiController
{
    // ...
}

或者:

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

        // 應(yīng)用自定義異常過(guò)濾器
        config.Filters.Add(new CustomExceptionFilterAttribute());
    }
}

這些方法可以幫助你在C# Web API中處理異常,確保應(yīng)用程序在遇到錯(cuò)誤時(shí)能夠返回適當(dāng)?shù)捻憫?yīng)。

0