我已经创建了一个简单的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");
}
}
}
答案 0 :(得分:0)
在控制器级别,您可以通过重写OnException方法来处理未处理的异常。
请查看此链接以获取描述:https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine
答案 1 :(得分:0)
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);
}
}
答案 2 :(得分:0)
.NET 4允许您定义任务如何处理异常,如以下文章所示:this article
因此,在上面的示例中,您将首先定义任务
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
}
答案 3 :(得分:0)
使用HttpServerUtility.HttpApplication.Server对象的方法GetLastError。
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
}