I am creating an ASP.NET MVC app and I would like it so when an error occurs I call another action which loads a different view.
public ActionResult Invoices()
{
invoiceClass invoice = getInvoice();
//do stuff with invoice
}
public invoiceClass getInvoice()
{
invoiceClass invoice = new invoiceClass();
try
{
// Do stuff
}
catch(exception e)
{
return RedirectToAction("Index");
}
return invoice;
}
I have a method that is very similar to this, when I step through the code, the exception is caught and it hits the redirect call then goes to the return and continues without redirecting. Am I missing something obvious?
If this is an HTTP entry point, you should be returning an ActionResult
.
public ActionResult stuff()
{
try
{
// Do stuff
}
catch (Exception e)
{
//Return a RedirectResult
return RedirectToAction("Index");
}
//Return a JsonResult
//Example: return the JSON data { "number": 1 }
return Json(new { number = 1 });
}
Here is how I would address your question given the edits you just made.
public ActionResult Invoices()
{
try
{
invoiceClass invoice = getInvoice();
//do stuff with invoice
return Json(...);
}
catch
{
//Catch the exception at the top level
return RedirectToAction("Index");
}
}
public invoiceClass getInvoice()
{
invoiceClass invoice = new invoiceClass();
// Do stuff; possibly throw exception if something goes wrong
return invoice;
}
you are missing a return
return RedirectToAction("Index");
And don't forget to change your return type to ActionResult
So Ive managed to find a solution to this problem however I'm certain there will be a better more efficient way.
public ActionResult Invoices()
{
try{
invoiceClass invoice = getInvoice();
//do stuff with invoice
}catch (exception e){
return RedirectToAction("Index");
}
}
public invoiceClass getInvoice()
{
invoiceClass invoice = new invoiceClass();
try
{
// Do stuff
}
catch(exception e)
{
index(); //<--the action result
}
return invoice;
}
calling index() runs through the method then throws an exception in the Invoices() method which then redirects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.