Rivka
Rivka

Reputation: 2202

Task.Status.Faulted - How to Handle Exceptions

I have the following task in my ASP.NET Web API that saves the incoming request as a file. It seems to work fine on my local, but on the hosting server, the file is not saved, and my logs indicate the status is Faulted.

As I understand, this has to do with unhandled exceptions. How can I find out what these exceptions are so I can resolve them?

    // Save file
    MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/Files"));
    Task<IEnumerable<HttpContent>> task = Request.Content.ReadAsMultipartAsync(provider);

    return task.ContinueWith<string>(contents =>
    {
        string filename = provider.BodyPartFileNames.First().Value;

        FileInfo file = new FileInfo(filename);

        Log.LogMessage("Status: " + task.Status.ToString() + " File Exists: " + file.Exists);

        // Delete excel file when complete.
        File.Delete(filename);

        // Return message to user.
        return "Complete";

    }, TaskScheduler.FromCurrentSynchronizationContext());

Upvotes: 2

Views: 3110

Answers (1)

Aliostad
Aliostad

Reputation: 81660

You need to have another continuation to look at the exception:

Task task1 = () => ....;
task1.ContinueWith((t) => if(t.IsFaulted) Trace.WriteLine(t.Exception.ToString()));
return task1;

So the trick is to still return the initial task while still defining a continuation on it.

Upvotes: 3

Related Questions