static void SendEmail(HttpException exception, string appName, MailAddress from, MailAddress to)
        {
            Trace.TraceInformation("[RazorRenderExceptionHelper]: Preparing to send email to developer");
            string body = exception.GetHtmlErrorMessage();
            bool   html = true;

            if (string.IsNullOrWhiteSpace(body))
            {
                body = exception.ToString();
                html = false;
            }

            string subject = string.Format("Exception for app: {0}, at {1}", appName, DateTime.Now);

            EmailExtensions.SendEmail(from, to, subject, body, !html,
                                      (message, ex) =>
            {
                if (ex == null)
                {
                    Trace.TraceInformation("[RazorRenderExceptionHelper]: Email was sent to {0}",
                                           to);
                }
                else
                {
                    Trace.TraceError("[RazorRenderExceptionHelper]: Failed to send email. {0}", ex.Message);
                    LogEvent.Raise(exception.Message, exception.GetBaseException());
                }
            });
        }
Example #2
0
        internal static void ThrowException(Application app, HttpException ex)
        {
            int status = ex.GetHttpCode();

            app.Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            app.Context.Response.StatusCode = status;
            Exception e = ex.GetBaseException();
            string    msg;

            if (e is TemplateException)
            {
                msg = FormatMessage(e.Message);
            }
            else
            {
                msg = string.Concat(@"<!DOCTYPE html>
<html>
<head>
<title>", status.ToString(), " ", HttpWorkerRequest.GetStatusDescription(status), @"</title>
</head>
<body>", FormatMessage(string.Concat(e.Message, "\r\n", e.StackTrace)), @"</body>
</html>");
            }
            app.Context.Response.Write(msg);
            app.Context.Response.End();
        }
 public HttpContextError(HttpException exception, HttpContextBase httpContext)
     : base(new Error(exception.GetBaseException()))
 {
     HttpContext   = httpContext;
     HttpException = exception;
     Error.WithLocation(HttpContext.GetUrl())
     .SetPlatform("ASP.NET");
 }
        public virtual void HandleError()
        {
            var server   = Application.Server;
            var response = Application.Response;

            Exception ex = server.GetLastError();

            HttpException httpException = ex as HttpException
                                          ?? new HttpException("Generic exception...", ex);

            var rootException = httpException.GetBaseException();

            Trace.TraceError("Exception: {0}", rootException.Message);

            if (IsProduction())
            {
                //log or send email to developer notifiying the exception ?
                LogAction(httpException);
                //server.ClearError();
            }

            var statusCode = httpException.GetHttpCode();

            //setar o statuscode para que o IIS selecione a view correta (no web.config)
            response.StatusCode        = statusCode;
            response.StatusDescription = rootException.Message; //todo: colocar uma msg melhor

            switch (statusCode)
            {
            case 404:
                break;     //IIS will handle 404

            case 500:
            {
                //check for exception type you want to show custom message
                if (rootException is TException)
                {
                    server.ClearError();
                    response.TrySkipIisCustomErrors = true;
                    response.Clear();

                    try
                    {
                        RenderCustomException(rootException as TException);
                    }
                    catch
                    {
                        //fallback to response.Write
                        response.Write(rootException.ToString());
                    }
                }
                break;         //IIS will handle 500
            }
            }
        }
        static void LogActionEx(HttpException exception)
        {
            var status = exception.GetHttpCode();

            if (status < 500)
            {
                return;
            }
            LogEvent.Raise(exception.Message, exception.GetBaseException());
            using (var smptClient = new SmtpClient())
            {
                //todo: Enviar async
                smptClient.Send("Admin", BootstrapperSection.Instance.Mail.MailDeveloper, "Exception " + status, exception.ToString());
            }
        }
        static void LogActionEx(HttpException exception)
        {
            var status = exception.GetHttpCode();

            if (status < 500)
            {
                return;
            }
            var cfg = BootstrapperSection.Instance;

            if (cfg.Mail.SendExceptionToDeveloper &&
                (HttpContext.Current == null || !HttpContext.Current.IsDebuggingEnabled))
            {
                ThreadPool.QueueUserWorkItem(x => SendEmail(exception, cfg.AppName, new MailAddress(cfg.Mail.MailAdmin, "Admin"),
                                                            new MailAddress(cfg.Mail.MailDeveloper, "Developer")));
            }
            else
            {
                LogEvent.Raise(exception.Message, exception.GetBaseException());
            }
        }
Example #7
0
        public virtual void HandleError()
        {
            var server   = ApplicationInstance.Server;
            var response = ApplicationInstance.Response;

            Exception ex = server.GetLastError();

            if (ex is ThreadAbortException)
            {
                //Esta exception é lançada quando utiliza-se Response.Redirect(url, true).
                //O correto é Response.REdirect(url, false); CompleteRequest()
                //mas em alguns casos, é necessário parar imediatamente o processamento da página,
                //lançando um threadabortexception com Response.End()
                Trace.TraceInformation("Ignoring Thread abort: " + ex.Message);
                return;
            }

            HttpException httpException = ex as HttpException
                                          ?? new HttpException("Generic exception...", ex);

            var rootException = httpException.GetBaseException();

            //todo: use HttpContext.Current.Items !!!

            //stores exception in session for later retrieval
            if (ApplicationInstance.Context.Handler is IRequiresSessionState ||
                ApplicationInstance.Context.Handler is IReadOnlySessionState)
            {
                // Session exists

                ApplicationInstance.Session["exception"] = rootException;
            }
            else if (HttpContext.Current != null)
            {
                HttpContext.Current.Items["exception"] = rootException;
            }

            Trace.TraceError("[ExceptionHelper]: {0}", rootException.Message);

            if (IsProduction())
            {
                //log or send email to developer notifiying the exception ?
                LogAction(httpException);
                server.ClearError(); //limpar o erro para exibir a página customizada
            }

            if (response.StatusCode == 302)
            {
                server.ClearError();
                return;
            }
            var statusCode = httpException.GetHttpCode();

            //setar o statuscode para que o IIS selecione a view correta (no web.config)
            response.StatusCode        = statusCode;
            response.StatusDescription = rootException.Message; //todo: colocar uma msg melhor

            switch (statusCode)
            {
            case 401: break;

            case 403:
            {
                if (ApplicationInstance.Request.IsAuthenticated && ApplicationInstance.Response.StatusCode == 403)
                {
                    bool isAjax = ApplicationInstance.Request.IsAjaxRequest();
                    if (!isAjax)
                    {
                        ApplicationInstance.Response.Write("Você está autenticado mas não possui permissões para acessar este recurso");
                    }
                }
                break;
            };

            case 404:
                break;     //IIS will handle 404

            case 500:
            {
                //check for exception type you want to show custom message
                if (rootException is TException)
                {
                    server.ClearError();
                    response.TrySkipIisCustomErrors = true;
                    response.Clear();

                    try
                    {
                        RenderCustomException(rootException as TException);
                    }
                    catch
                    {
                        //fallback to response.Write
                        response.Write(rootException.ToString());
                    }
                }
                break;         //IIS will handle 500
            }

            default:
            {
                break;
            }
            }
        }