-1

I am aware of the fact that await operator is clean and if used with async/await all the way down it will throw the exceptions properly.

I have a bulk of API calls (Web API) written in controllers which uses async await all the way down. Is there any way to write a common try catch for all those async await methods or do I need to go for a harder way to add try catch in each of those API methods to handle all the unhandled exceptions.

Raghav
  • 8,772
  • 6
  • 82
  • 106
  • Why do you want a “Global try catch handler”? [What problem do you think that's going to solve](https://meta.stackexchange.com/questions/66377/)? – Dour High Arch Apr 29 '19 at 01:14
  • I need a common try catch just like ApplicationOnError method of Global.asax so that a common logic can be written. – Raghav Apr 29 '19 at 03:47

1 Answers1

1

You can write an exception filter.

Note that exception filters apply whether or not the method is async. The same exception filter will work fine for both synchronous and asynchronous methods that throw exceptions.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thanks. I knew you will come and save the world from being stuck in async await issues :) – Raghav Apr 29 '19 at 18:19
  • I am stuck with another issue which I posted two days back https://stackoverflow.com/questions/55836889/async-await-value-does-not-fall-within-the-expected-range Since I didn't get any pointers there I am planning to remove Task.Run and Thread.Startnew entirely in my ASP.NET project. I feel that could be the cause of that issue. – Raghav Apr 29 '19 at 18:23
  • I went through your this article https://stackoverflow.com/questions/33764366/is-task-run-considered-bad-practice-in-an-asp-net-mvc-web-application and got this "That’s why one of the principles of ASP.NET is to avoid using thread pool threads (except for the request thread that ASP.NET gives you, of course). More to the point, this means that ASP.NET applications should avoid Task.Run." That made me decide to remove Task.Run and Thread.StartNew from entire ASP.NET application. – Raghav Apr 29 '19 at 18:23
  • Will this filter work if I have multiple awaits in a single async method? What if the first await methods throws the exception while the second await Task was running? Where will second await Task exception be handled? – Raghav May 01 '19 at 06:56
  • @Raghav: The filter works for any exceptions propagated by an action method. In order to propagate exceptions, all tasks must (eventually) be `await`ed by the action method. – Stephen Cleary May 01 '19 at 12:29