Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - Send e-mail whenever an exception occurs

Hi and thanks for taking the time to answer my question.

I have an asp.net webforms application that I built for internal purposes of a medium sized company.

First off let me say that I handle all exceptions that might happen during CRUD operations and show the appropriate message to the user. However, is there a way that I can, in a centralised manner, first email the innerException message to myself along with the stack trace, and then show the message to the user?

In other words, I dont want to create a method like EmailException() and call it in every catch(Exception ex) block but I'd like to call it once somewhere where all exceptions are first caught.

If my question is not clear enough please tell me.

Thanks again!

like image 363
Dragan Avatar asked Dec 12 '12 17:12

Dragan


2 Answers

Elmah is great, but Log4Net will also give you that capability, along with other logging capabilities. You just need to add an SmtpAppender definition to your log4net config, along with whatever other appenders you want/need/desire.

Simple, easy to do. And the easiest way to catch any unhandled exceptions is by adding an Application_Error() method to your global.asax. It is invoked by the Asp.Net runtime and will catch

all unhandled ASP.NET errors while processing a request — in other words, all the errors that are not caught with a Try/Catch block or in a page-level error handler.

It should be noted that Elmah, log4net and the global.asax Application_Error() method all coexist happily. Elmah just sits there, sotto voce, and listens, logging any exceptions that pass by.

like image 98
Nicholas Carey Avatar answered Sep 30 '22 14:09

Nicholas Carey


Elmah is perfect for this:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception, including colored stack traces. *In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.

Here's a config example.

like image 38
Michael Haren Avatar answered Sep 30 '22 15:09

Michael Haren