gpt4 book ai didi

c# - 捕获异常并在我的自定义错误处理程序中处理

转载 作者:行者123 更新时间:2023-12-03 08:52:44 24 4
gpt4 key购买 nike

我在Global.asax中定义了自定义错误处理程序:

void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();

var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;

if(httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch(Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}

IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);

}

我试图通过在服务模型中引发这样的错误来测试我的错误处理程序:
if(albums != null)
{
albums = null;
ctx.SpotifyAlbums.AddRange(albums);
ctx.SaveChanges();
}

这引发了一个异常,但是如何使用我的自定义错误处理程序“捕获”该异常?

最佳答案

我通常会创建带有引发特定异常的 Action 的 Controller 。

public class ErrorTestController : Controller
{
public ActionResult ThrowHttpException(int httpStatusCode)
{
throw new HttpException(httpStatusCode, "Error!");
}

public ActionResult ThrowApplicationError()
{
Throw new Exception("Boo!");
}
}

不花哨,但能胜任。 404处理程序最容易测试-只需输入错误的网址即可。

关于c# - 捕获异常并在我的自定义错误处理程序中处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36868665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com