TransWikia.com

Is there a way to redirect to a new page is System.NullReferenceException is triggered?

Stack Overflow Asked by Th3Ent1ty on November 12, 2021

I have my code configured in a way that it pulls the userid from asp.net identity and then checks to see if it’s associated with a candidate id to load the view candidate page for that user.

Naturally, if that candidate id is null, it throws the exception.

Is there a way for me to tell the controller that if that exception is thrown redirect to new action?

I’ve tried if statements like If (candidate.CandidateId < 1 || candidate.CandidateId.ToString() == null), but either way that exception pops because candidate Id is null.

One Answer

It sounds like you're drastically overthinking it. There's really no reason to involve exception handling here, and one shouldn't rely on exception handling for application logic.

If the problem is that candidate is null, then check if candidate is null:

if (candidate == null)
{
    // perform redirect and return
}
// the rest of your logic relying on candidate

In the question you state that what's actually null is CandidateId. This sounds far less likely to me, but I suppose it may be possible in your setup. If that's the case, the structure is still the same:

if (candidate.CandidateId == null)
{
    // perform redirect and return
}
// the rest of your logic relying on candidate.CandidateId

Or if CandidateId is a Nullable<T>:

if (!candidate.CandidateId.HasValue)
{
    // perform redirect and return
}
// the rest of your logic relying on candidate.CandidateId

Answered by David on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP