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?
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.
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.
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.
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>
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With