Handling 404 errors in DD4T

DD4T, Tridion

When dealing with errors in DD4T, especially when you are running locally in your development environment, 404 errors can become quite a regular thing.
You can go with the classic 404 configuration from the Web.Config, but then your DD4T environment will debug the errors in Visual Studio each time. Can be quite frustrating when this happens a lot.
To implement a nice 404 page, that doesn't take you into debug mode in Visual studio, you can try the following code changes to your page controller:

public override ActionResult Page(string pageId)
{
    try
    {
        //If the page is found, return the page
        return base.Page(pageId);
    }
    catch (SecurityException se)
    {
        //This could be changed using the same construction
        throw new HttpException(403, se.Message);
    }
    catch (PageNotFoundException pnfe)
    {
        //If the page can't be found
        return PageNotFound(pageId);
    }
    catch (HttpException httpe)
    {
        //Yeah, sometimes it is a HttpException and not a PageNotFound Exception, better to be safe than sorry
        if (httpe.GetHttpCode() == 404)
        {
            //404, Page not found
            return PageNotFound(pageId);
        }
        //Otherwise, throw an error
        throw httpe;
    }
}

private ActionResult PageNotFound(String url)
{
    //Force 404 status code
    Response.StatusCode = 404;
    //Force IIS to skip its default 404 error page
    Response.TrySkipIisCustomErrors = true;
    //Return our own content editable 404 page
    return base.Page("System/ErrorPages/404.html");
}

This can be used for other type of errors as well, as the 403 error being caught and thrown here. This allows for content editable error pages, and no more Debug sessions in Visual Studio. You can still set breakpoints if you want to know what happens in there.