Acaz Souza
Acaz Souza

Reputation: 8641

How to log 404 erros from .net mvc3 global filters using HandleErrorAttribute?

i'm trying to log 404 erros from my derived class from HandleErrorAttribute.

Here is my class:

public class LogExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext exceptionContext)
    {
        Log.LogException(exceptionContext.Exception, exceptionContext.Exception.Message);
        base.OnException(exceptionContext);
    }
}

I get all exceptions in application, but i'm not getting 404 erros. I want to get all kind of erros, exceptions.

Upvotes: 1

Views: 1675

Answers (3)

Tien Do
Tien Do

Reputation: 11079

You can still catch all errors in Application_Error. You can also handle 404 error specifically by modifying customErrors section in the Web.config file.

Upvotes: 2

Hector Correa
Hector Correa

Reputation: 26690

This other post has some information that you might find useful if you want to understand what's going on under the hood:

Error Handling in ASP.NET MVC

Upvotes: 0

Richard
Richard

Reputation: 22026

You will need a catchall route which is registered last and then responds with 404 after the controller has logged the error:

 routes.MapRoute(
                                "NotFound", 
                                "{*url}", 
                               new {controller = "NotFound", action = "index"}
                               )


public class NotFoundController: Controller 
{
    public ActionResult Index(string url)
    {
            Log.Warn(this, string.Format("404 Request Not Found: {0}", url));
            Response.StatusCode = 404;
            var model = new NotFoundViewModel
                            {
                                Title = "Sorry but the page you are looking for does not exist",
                                Message = new HtmlString("Please <a href='/'>click here</a> to return to the home page")
                            };

            return View("404", model);
     }

}

Upvotes: 5

Related Questions