Convert an exception into HTTP 404 response in the Application_Error

Posted by Dmitriy Nagirnyak on Stack Overflow See other posts from Stack Overflow or by Dmitriy Nagirnyak
Published on 2010-05-11T04:41:01Z Indexed on 2010/05/20 22:50 UTC
Read the original article Hit count: 693

Hi,

First of all, quickly what exactly I want to achieve: translate particular exception into the HTTP 404 so the ASP.NET can handle it further.

I am handling exceptions in the ASP.NET (MVC2) this way:

    protected void Application_Error(object sender, EventArgs e) {
        var err = Server.GetLastError();
        if (err == null)
            return;
        err = err.GetBaseException();

        var noObject = err as ObjectNotFoundException;
        if (noObject != null)
            HandleObjectNotFound();

        var handled = noObject != null;
        if (!handled)
            Logger.Fatal("Unhandled exception has occured in application.", err);
    }

    private void HandleObjectNotFound() {
        Server.ClearError();
        Response.Clear();
        // new HttpExcepton(404, "Not Found"); // Throw or not to throw?
        Response.StatusCode = 404;
        Response.StatusDescription = "Not Found";
        Response.StatusDescription = "Not Found";
        Response.Write("The whole HTML body explaining whata 404 is??");
    }

The problem is that I cannot configure default customErrors to work with it. When it is on then it never redirects to the page specified in customErrors: <error statusCode="404" redirect="404.html"/>.

I also tried to raise new HttpExcepton(404, "Not Found") from the handler but then the response code is 200 which I don't understand why.

So the questions are:

  1. What is the proper way of translating AnException into HTTP 404 response?
  2. How does customErrors section work when handling exceptions in Application_Error?
  3. Why throwing HttpException(404) renders (blank) page with success (200) status?

Thanks,
Dmitriy.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about error-handling