Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best practice for returning a error in asp.net mvc

This is my Action method

var model= db.PageData.FirstOrDefault();
if (model==null)
{
    //return Error
}

reutrn View(model);

What is the best practice for returning this error? In a userfriendly way and in a way that I could identity this error when it occurs.

like image 855
Hossein Panahloo Avatar asked Apr 27 '15 12:04

Hossein Panahloo


3 Answers

Throw a 500 Error:

return new HttpStatusCodeResult(500);

And then handle 500 errors in your web.config.

http://benfoster.io/blog/aspnet-mvc-custom-error-pages

like image 118
Curtis Avatar answered Nov 05 '22 01:11

Curtis


I would create an Error view and then do something like this if you are expecting an error:

if(model == null)
{
    ViewBag.Error = "Your x is not present, please try again later or contact xxx";
    return View("Error");
}

On your error view then just check if ViewBag.Error is present. (Error view should be in shared views).

Note I would only do this when you are excepting it to happen and you then can inform the users what they have done wrong. e.g. Editing something, you could return them this view and give them some more information to what they have done wrong.

like image 30
Jamie Rees Avatar answered Nov 05 '22 02:11

Jamie Rees


Global Error handling in MVC

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        Server.ClearError();
        Response.Redirect("/Home/Error");
    }
}

see here for error hadling in asp.net mvc

like image 1
Jega Avatar answered Nov 05 '22 01:11

Jega