Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have the following code in my startup.cs to email any errors in the application:

app.UseExceptionHandler(
    options =>
    {
        //options.UseDeveloperExceptionPage();
        options.Run(
            async context =>
            {
                var ex = context.Features.Get<IExceptionHandlerFeature>();
                if (ex != null)
                {
                    var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.Source}<hr />{context.Request.Path}<br />";
                    err += $"QueryString: {context.Request.QueryString}<hr />";

                    err += $"Stack Trace<hr />{ex.Error.StackTrace.Replace(Environment.NewLine, "<br />")}";
                    if (ex.Error.InnerException != null)
                        err +=
                            $"Inner Exception<hr />{ex.Error.InnerException?.Message.Replace(Environment.NewLine, "<br />")}";

                    if (context.Request.Form.Any())
                    {
                        err += "<table border=\"1\"><tr><td colspan=\"2\">Form collection:</td></tr>";
                        foreach (var form in context.Request.Form)
                        {
                            err += $"<tr><td>{form.Key}</td><td>{form.Value}</td></tr>";
                        }
                        err += "</table>";
                    }

                    await msg.SendEmailAsync(appSettings.Value.ErrorDeliveryEmailAddress, "CMP v2 error",
                        err);
                    context.Response.Redirect("/Home/Error?r=" +
                                                System.Net.WebUtility.UrlEncode(context.Request.Path + "?" +
                                                                                context.Request.QueryString));
                }
            });
        //options.UseExceptionHandler("/Home/Error");
        //options.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
    }
);

However, it does pick up 404 errors.

How can I use the:

app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

Code, and still email the error details to a support queue?

share|improve this question

If you add this to your Configure method in Startup.cs, then you can catch and handle 404 errors:

  app.Use(async (context, next) =>
  {
    await next();
    if (context.Response.StatusCode == 404)
    {
      //handle the 404 response here
    }
  });
share|improve this answer
    
Is there a way to use app.UseStatusCodePagesWithReExecute("/Home/Error/{0}"); - would that just go under await next()? – RemarkLima 2 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.