Ayo Adesina
Ayo Adesina

Reputation: 2395

Send email on 500 Error Asp.net MVC

If a 500 exception error occurs in my MVC application I want to send an email to alert the website owners.

I have discovered the Application_Application_Error method on the global.asax.cs file, which fires when ever the application has an error.

What I want to know is, is it safe to send an email in this method, what happens if an unexpected error happens? Will the application end up in an infinate loop? kill my webserver?

Has anyone done something like this before, is there a better way?

Upvotes: 0

Views: 1430

Answers (2)

Uladz
Uladz

Reputation: 1968

Usually some kind of library is used to perform logging: Nlog, log4net, Serilog or others. And most of such libraries have an ability to perform email notifications. You could use this knowledge — perform simple and consistent logging in your app and achieve goals with proper configuration for logger of your choice.

This could be done with use of:

Upvotes: 0

Wurd
Wurd

Reputation: 475

If you are using MVC, why not use an action filter that you can add to your entire app?

public class CustomErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        try{
            //Send email
        }
        catch{
           //Swallow...
        }
        base.OnException(filterContext);
    }
}

Then in your FilterConfig.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new CustomErrorHandler());       
}

If you swallow the exception in the filter then it doesn't bubble up and create any loops in your app. Plus you can have more fine grain control over your error handling.

Upvotes: 4

Related Questions