Reputation: 6095
I want to handle all errors at one place without referencing that class.
see my current structure.
public ActionResult Login(string returnUrl)
{
try
{
var a = 10;
var b = 0;
var c = a / b;
}
catch (Exception ex)
{
throw new LogEroor("", ex);
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
and my error handling class.
public class LogEroor : Exception
{
public LogEroor(string message, Exception Ex) : base(message, Ex)
{
// error handling
}
}
My question
Is there any way that I can call LogError method with Ex parameter when error occurs, but I do not want to call this method in each and every catch, like I did over here.
Upvotes: 0
Views: 1796
Reputation: 37000
How do you expect to call a method or even a constructor without specifiying it? What you want makes no sense at all, of course all your classes have to reference the generic exception-class if they´re up to throw one.
You could register to the AppDomain.UnhandledExceptionHandler
however which is a generic handler for all not handled exceptions. So instead of catching all your exceptions and throwing them again by whrapping them you can use this:
AppDomain.UnhandledExceptionHandler += (sender, args) => { throw new LogError(args.ExceptionObject); };
But this way you would throw an exception within the last layer of exception-handling your app has. This means you throw an exception which is never caught and will make your app crash. To avoid this implement your logging directly within that event.
Upvotes: 1
Reputation: 151586
This is a typical XY problem. The actual problem X you're trying to solve is, paraphrased:
I want to log all exceptions that occur in my web application.
Your solution Y is, paraphrased:
I will inherit from Exception, in which I will do the logging, and want any exception that is thrown to be converted to my exception type so it can be logged, without writing a try-catch block in all places where exceptions can occur.
Now you want help with problem Y, but that's the wrong approach altogether. You could do it using the AppDomain.UnhandledException
event, but you shouldn't.
Your solution is in How do I log ALL exceptions globally for a C# MVC4 WebAPI app?: use exception filters.
Upvotes: 4