0

I've created a simple MVC project, add one method:

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";
    }
}

Then i run application, get "ASD" output and debug messages:

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

But how can I catch that exception? I've tried creating Application_Error method on global.asas, but it didn't work:

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");
        }
    }
}
DTXqueque
  • 332
  • 2
  • 12
  • Are you looking for a way to catch Exceptions arising from Task.Run? – mahlatse Jan 31 '19 at 14:34
  • @mahlatse Kind of, without using await. – DTXqueque Jan 31 '19 at 18:36
  • Have you tried [https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library) – mahlatse Jan 31 '19 at 18:57

4 Answers4

0

At the controller level, you can deal with unhandled exceptions by overriding the OnException method.

Look at this link for a description: https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

Charles Owen
  • 2,403
  • 1
  • 14
  • 25
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);
 }
}
avg_bloke
  • 194
  • 1
  • 11
0

.NET 4 allows you to define how your task will handle exceptions as shown in the following post : catch exception that is thrown in different thread

So in your example above, you would first define your task

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

then pass in an exception handler

task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);

then finally define an exception handler somewhere

static void ExceptionHandler(Task<string> task)
{
    var exception = task.Exception;
    //Handle error via ModelState or how you prefer 
}
PaulBinder
  • 2,022
  • 1
  • 16
  • 26
0

Use the HttpServerUtility.HttpApplication.Server object's method GetLastError.

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
}
Daniel
  • 1,044
  • 11
  • 10