Question

I have a controller action like this:

public ActionResult Index(string url)
{
     var pageTitle = url.Split('/')[0];
     var page = Services.PageService.GetPage(pageTitle);

     if (page == null)
     {
         throw new HttpException((Int32) HttpStatusCode.NotFound, "NotFound");
     }

      return View(page);
 }

Everytime I am debugging my site, when the HttpException is thrown I get a prompt from Visual Studio notifying me that the exception was unhandled by user code.

I guess I just want somebody to clarify that what I am doing is correct, and that this notification can be dismissed without worry. The event still bubbles up to the Application_Error method in my Global.asax file where I am actually handling HttpException's, so as far as I can tell the only problem is the inconvenience of VS telling me every time this exception is thrown.

Was it helpful?

Solution

I guess I just want somebody to clarify that what I am doing is correct, and that this notification can be dismissed without worry.

Yes, what you are seeing is called a first chance exception. VS debugger notifies you of all exceptions occurring in your code. If you have a proper handler for this exception you should be fine.

OTHER TIPS

I assume you want to return the http code (a 404 in this case) to the user/consumer of your page. So you should rather do this:

public ActionResult Index(string url)
{
     var pageTitle = url.Split('/')[0];
     var page = Services.PageService.GetPage(pageTitle);

     if (page == null)
     {
        return new HttpNotFoundResult();
     }
      return View(page);
 }

The HttpNotFoundResult is a new ActionResult in asp.net-mvc3, there is also a protected method HttpNotFound() as part of the controller class which does the same thing. In both cases you can also supply a message string.

Returning an ActionResult is also more graceful I think in terms of unit-testing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top