在C# WebAPI中處理異常通常可以通過以下方法:
try
{
// code that may throw an exception
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An error occurred: " + ex.Message);
}
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred: " + context.Exception.Message),
ReasonPhrase = "Internal Server Error"
};
context.Response = response;
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var ex = context.Error;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("An error occurred: " + ex.Message);
});
});
}
}
這些方法可以幫助您在C# WebAPI中有效地處理異常,根據具體需求選擇合適的方式來處理異常。