How to create an exception with redirection to user-friendly error page in MVC
-
25-07-2021 - |
سؤال
I have an MVC action which generates a Word document:
[HttpGet]
public ActionResult ExportToWord(string docId)
{
try
{
//...
//Word-document generating is done here...
//...
return File(stream, MIMEAssistant.GetMIMEType("docx"), fileName + ".docx");
}
catch (Exception e)
{
throw new Exception("Problem with generating! " + e.ToString());
}
If I have so I get en Asp.Net standard exception with URL
http://localhost:18314/Export/ExportToWord?docId=5
If I have so I have the same URL. Redirection is not done. It must go to
http://localhost:18314/Home/ErrorPage.
Now users do not get any error page, just reloading of the page. The page is reloaded not correctly because the URL is
http://localhost:18314/Export/ExportToWord?docId=5
I hope it was understandable description :)
Question: How to make correct redirection to .../Home/ErrorPage and send an exception by using Elmah logging facility?
المحلول
You can return RedirectToAction("ErrorPage", "Home");
instead of throwing exception. There are RedirectToAction
overloads which allows to pass route values (so you can pass your error id, exception type etc).
UPDATE
As you want to log exceptions using ELMAH, then I suggest logging errors manually and redirecting to action with:
catch(Exception e)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
return RedirectToAction("ErrorPage", "Home");
}