global error handle loggs to Email

 using Harsco.AFIWeb.API.Helpers;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.Filters;

using Microsoft.AspNetCore.Mvc.ModelBinding;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Threading.Tasks;

using Microsoft.Extensions.Logging;

using Harsco.EmailService;


namespace Harsco.AFIWeb.API.Filters 

{

    public class ApiExceptionFilter : IExceptionFilter

    {

        private readonly IHostingEnvironment _hostingEnvironment;

        private readonly IModelMetadataProvider _modelMetadataProvider;

        private readonly ILogger<ApiExceptionFilter> _logger;

        private readonly EmailConfiguration _emailConfig;

        private readonly EmailConfigService _emailConfigService;


        public ApiExceptionFilter(IHostingEnvironment hostingEnvironment, IModelMetadataProvider modelMetadataProvider, ILogger<ApiExceptionFilter> logger, EmailConfiguration emailConfig, EmailConfigService emailConfigService)

        {

            _hostingEnvironment = hostingEnvironment;

            _modelMetadataProvider = modelMetadataProvider;

            _logger = logger;

            _emailConfig = emailConfig;

            _emailConfigService = emailConfigService;

        }


        public void OnException(ExceptionContext context)

        {

            // Log the exception

            _logger.LogError(context.Exception, "Unhandled exception occurred.");


            // Send email notification

            try

            {

                var toList = new List<string> { "jreddy@enviri.com", "pkadma@enviri.com" };

                var subject = $"[AFIWeb] Unhandled Exception: {context.Exception.GetType().Name}";

                var content = $"<b>Message:</b> {context.Exception.Message}<br/><b>Stack Trace:</b><br/>{context.Exception.StackTrace?.Replace("\n", "<br/>")}";

                var emailService = new EmailService.EmailService(_emailConfig, _emailConfigService);

                var message = new Message(toList, subject, content, null);

                emailService.SendEmail(message);

            }

            catch (Exception ex)

            {

                _logger.LogError(ex, "Failed to send error notification email.");

            }


            var errorResponse = new

            {

                Message = "An unexpected error occurred. Please contact support if the problem persists.",

                // Optionally add a trace id or timestamp

                TraceId = context.HttpContext.TraceIdentifier

            };


            context.Result = new ObjectResult(errorResponse)

            {

                StatusCode = 500

            };

            context.ExceptionHandled = true;

        }

    }

}


Comments

Popular posts from this blog

on mouse hover show icons