Base solution for your next web application
Open Closed

Email notifications for exceptions #6319


User avatar
1
Sbasso58 created

Hi,

I'm wondering if there is some built-in mechanism to receive email notifications when an unhandled exception occurs. Something like Elmah does on Web Api 2.

Thanks


2 Answer(s)
  • User Avatar
    2
    alper created
    Support Team

    There's a good catch point to handle all exceptions.

    public class MyExceptionHandler : IEventHandler<AbpHandledExceptionData>, ITransientDependency
    {
        public void HandleEvent(AbpHandledExceptionData eventData)
        {
            // Send the exception to your email!  Use => eventData.Exception!
        }
    }
    

    https://aspnetboilerplate.com/Pages/Documents/Handling-Exceptions#exception-event

  • User Avatar
    0
    Sbasso58 created

    Thanks for your guidance. This is what I have at the moment. Maybe it can help somebody else:

    public class GlobalExceptionEventHandler : IEventHandler&lt;AbpHandledExceptionData&gt;, ITransientDependency
        {
            private readonly IEmailSender _emailSender;
            private readonly IConfigurationRoot _configurationRoot;
    
        public GlobalExceptionEventHandler(IEmailSender emailSender, IConfigurationRoot configurationRoot)
        {
            _emailSender = emailSender;
            _configurationRoot = configurationRoot;
        }
    
        public void HandleEvent(AbpHandledExceptionData eventData)
        {
            string subject = eventData.Exception?.Message.TruncateWithPostfix(200).CleanUpSubject();
    
            if (!string.IsNullOrWhiteSpace(subject))
            {
                string exceptionDetails = eventData.Exception?.ToString();
    
                string recipient = _configurationRoot["ErrorEmailRecipient"];
    
                _emailSender.Send(recipient, subject, exceptionDetails, false);
            }
        }
    }