Yes you can.
Your question has already been answered in some capacity here
Here are four examples using different project types:
ASP.NET Core MVC by implementing a custom ExceptionFilterAttribute
:
public class MyExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
Logger.Error(ex);
}
}
[Route("api/[controller]")]
[MyExceptionFilter]
public class HomeController : Controller
{
// Action methods
}
ASP.NET MVC by overriding OnException
in your controller:
protected override void OnException(ExceptionContext context)
{
if (context.ExceptionHandled)
{
return;
}
Logger.Error(context.Exception);
context.Result = RedirectToAction(MVC.Error.Application());
context.ExceptionHandled = true;
}
Windows Application by subscribing to UnhandledException
event:
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
}
Web Forms by adding Application_Error
handler in global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Logger.Error(ex);
}