Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render error view when we encounter an exception

Tags:

c#

asp.net-mvc

How can I do this in another way ?

public ActionResult SomeAction(int id)
{
    try
    {            
        var model = GetMyModel(id);
        return View(model);
    }
    catch(Exception e)
    {
        var notFoundViewModel = new NotFoundViewModel { Some Properties };
        return View("~/Views/Shared/NotFound.cshtml", notFoundViewModel);
    }
}

Exception will be thrown for url Controller/SomeAction/NotFoundId. I hate to have in project something like: ~/Views/Shared/NotFound.cshtml.

like image 327
Razvan Dumitru Avatar asked Mar 23 '23 21:03

Razvan Dumitru


2 Answers

I realize this question is a few years old, but I figured I would add to the accepted answer. Following CodeCaster's recommendation of using the standard "Error.cshtml" as the file (view) to act as your generic error page, I recommend you let the MVC framework do the rest of the work for you.

If you place the Error.cshtml file in the Shared folder in your MVC project, you do not need to explicitly specify the path to the view. You can rewrite your code like the following:

public ActionResult SomeAction(int id)
{
    try
    {            
        var model = getMyModel(id);
        return View(model);
    }
    catch(Exception e)
    {
        var NotFoundViewModel = new NotFoundViewModel { Some Properties };
        return View("Error", NotFoundViewModel);
    }
}

In fact, I've noticed that if you supply an explicit path and are running the Visual Studio IIS Express on your local machine, it sometimes isn't able to find the file and displays the generic 404 message :(

like image 94
Savantes Avatar answered Mar 25 '23 10:03

Savantes


You can return HttpNotFoundResult object as:

catch(Exception e)
{
    return new HttpNotFoundResult();
}

or

catch(Exception e)
{
    return HttpNotFound("ooops, there is no page like this :/");
}
like image 41
Tolga Evcimen Avatar answered Mar 25 '23 10:03

Tolga Evcimen