Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch exception of MVC view?

In controller, try...catch can catch exception. How to catch exception in view? for example, a view may have code like:

<%= Html.Encode(Model.MyID)%>

If Model is null, you will get exception when access the view. where to catch the exception and redirect user to a error page with user-friendly error message?

like image 438
KentZhou Avatar asked Jul 02 '09 14:07

KentZhou


People also ask

Can we use try catch in MVC?

Even you can have Try –catch block inside Try block. In this article, we will be discussing various ways of handling an exception in ASP.NET MVC. Now, let's elaborate one by one. This is the default way of handling exceptions where we write our source code into the try block and catch the exceptions in the catch block.

How do we map the error to the view in MVC?

To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.

Which of the following codes shows how exceptions are handled in MVC?

The HandleErrorAttribute is the default implementation of IExceptionFilter. This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web. config.


2 Answers

You can use try/catch in a script block in the view:

@try
{    
  <div>typical Razor view stuff here...</div>
}
catch (Exception ex)
{
  @<script type="text/javascript">
    alert('@ex.Message.Replace("'","\\'").Replace("\r\n","<br/>")');
  </script>
}
like image 179
Paul Schaeflein Avatar answered Sep 29 '22 01:09

Paul Schaeflein


Although I support David Liddle's answer ("This logic should be handled inside your Controller and not the View") I can also tell you that you should code defensively in general.

For example instead of

try
{
    Html.Encode(Model.MyID)
}
catch
{
    Response.Redirect("~/Error/500");
}

you should

if (Model == null)
{
    // ...
}
else
{
    //.....
}

(ofcourse, again, don't put view selection logic in a view)

like image 41
Andrei Rînea Avatar answered Sep 28 '22 23:09

Andrei Rînea