如何在 MVC 中捕获未处理 ASP.NET 错误



我创建了一个简单的 MVC 项目,添加一个方法:

public class HomeController : Controller
{
    public async Task<string> Index()
    {
        var t = Task.Run(() =>
        {
            Debug.Print("Debug___1");
            throw new Exception("Error #1");
            Debug.Print("Debug___2");
        });
        await Task.Delay(5000);
        return "ASD";
    }
}

然后我运行应用程序,获取"ASD"输出和调试消息:

Debug___1
Exception thrown: 'System.Exception' in WebApplication2.dll

但是我怎样才能捕获该异常呢?我尝试在global.asas上创建Application_Error方法,但它不起作用:

namespace WebApplication2
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            Debug.Print("Catched");
        }
    }
}

在控制器级别,可以通过重写 OnException 方法来处理未经处理的异常。

查看此链接以获取说明:https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

catch(Exception ex)
{
 //create custom error handling method
 ErrorLog(ex);
}
Public static void Errorlog(Exception ex)
{
//creates new txt file to view errordetails
 string strPath = @"D:ErrorLog.txt";
 File.create(strPath);
 using (StreamWriter sw = File.AppendText(strPath))
 {
   sw.WriteLine("Error Details",+DateTime.Now);
   sw.WriteLine("Error Message: " + ex.Message);
   sw.WriteLine("Stack Trace: " + ex.StackTrace);
 }
}

.NET 4 允许您定义任务将如何处理异常,如以下帖子所示: 捕获在不同线程中抛出的异常

因此,在上面的示例中,您将首先定义您的任务

Task<string> task = new Task<string>(Test);

然后传入异常处理程序

task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);

然后最后在某处定义一个异常处理程序

static void ExceptionHandler(Task<string> task)
{
    var exception = task.Exception;
    //Handle error via ModelState or how you prefer 
}

使用 HttpServerUtility.HttpApplication.Server 对象的方法 GetLastError。

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
}

最新更新