8

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Hossein Panahloo
  • 520
  • 4
  • 18
  • I'd create an error page and call RedirectToAction("MyError", "ErrorController"). I'm sure someone will give a very in depth answer though. – Heberda Apr 27 '15 at 12:50
  • 2
    Possible duplicate: http://stackoverflow.com/questions/10732644/best-practice-to-return-errors-in-asp-net-web-api – Der Kommissar Apr 27 '15 at 12:50

4 Answers4

6

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

Curtis
  • 101,612
  • 66
  • 270
  • 352
1

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.

Jamie Rees
  • 7,973
  • 2
  • 45
  • 83
1

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

Edi G.
  • 2,432
  • 7
  • 24
  • 33
Jega
  • 33
  • 7
-1
if(model == null)
{
    TempData["Error"] = "Your x is not present, please try again later or contact 

    return View();
}

on your cshtml page you can check if temp data contain "Error entry", you can display your user detailed info.

@if (TempData["Error"] != null)
{
    <div class="error">
    @TempData["Error"].ToString
    </div>
}
Jacek
  • 11,661
  • 23
  • 69
  • 123
  • I wouldn't used TempData in this example, since tempdata is linked to the session and can easily be destroyed. For small messages possibly but if you need to give anything important to the user then a simply F5 and it's gone. But I guess everyone has their own preferences. – Jamie Rees Apr 27 '15 at 13:02
  • Yes, you have right. Life time of TempData is very short. I want to show simple method to pass detailed info to the same page – Jacek Apr 27 '15 at 13:04