1

Is there a way of using RedirectToAction where getting "Object reference not set to an instance of an object." error?

public ActionResult Details()
{
    if(NullReferenceException == TRUE)
    {
    return RedirectToAction("Create");
    }
    else
    {
    return View("Details");
    }
}

I need only a hint not a working solution. Thanks for any help.

Leri
  • 12,367
  • 7
  • 43
  • 60
Chris Hermut
  • 1,708
  • 3
  • 17
  • 32
  • 1
    You could use a try-catch ? – Jens Kloster Nov 16 '13 at 14:53
  • 1
    @JensKloster However exception handling mechanism is slightly heavy. So it would be more advisable to check if object is null and redirect if it is. Honestly, _I think_, that production code should not be handling `NullReferenceException` because it should not be thrown at all, unless something bad occurs. – Leri Nov 16 '13 at 14:56
  • 1
    @Leri I agree - my comment was just a brain dump :) – Jens Kloster Nov 16 '13 at 15:01

2 Answers2

1

This is what HandleError attribute (and functionality) exists for.

[HandleError]
public class YourController: Controller
{
    [HandleError] // or here
    public ActionResult YourAction()
    {
        // code
        return View();
    }
}
Community
  • 1
  • 1
Agat
  • 4,577
  • 2
  • 34
  • 62
1

You can:

  • override OnException method inside the controller
  • use the HandleError attribute (can be configured per exception type)

small example using both:

    [HandleError(ExceptionType=typeof(NullReferenceException), View="Error")]
    public string Home(string name)
    {
        ...
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
        {
            return;
        }
        // do something
        base.OnException(filterContext);
    }
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
  • 2
    I don't develop with asp.net mvc, however I do lots of networking stuff with .NET and I bet handling `NullReferenceException` like that will become debugging nightmare one day. – Leri Nov 16 '13 at 15:19