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.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With