Exception handling
References
Creating and Throwing Exceptions
Catch
Ensure the error is logged in a catch
.
Actions returning a page, view or partial should return the appropriate error page.
Return the correct notification to user if elements are changed during execution or for AJAX/JSON responses.
// Log error
// Return correct error page/partial
public PartialViewResult PersonalDetails(int discussionId)
{
try
{
return PartialView("_DiscussionPersonalDetails", new DiscussionPersonalDetailsViewModel(SessionHandler, discussionId));
}
catch (Exception ex)
{
ErrorUtilities.LogException(ex);
return PartialView("_Error");
}
}
// Log error
// Return correct error notification
[HttpPost]
public ActionResult Approve(int id, DiscussionSection activeTab)
{
try
{
ApproveDiscussion(id, DiscussionStatus.COMPLETED);
return Json(new { success = true, message = "Successfully approved.", redirectUrl = Url.EncryptedAction("Index", new { id, activeTab }) });
}
catch (Exception ex)
{
ErrorUtilities.LogException(ex);
return Json(new { success = false, message = "There was a problem saving this section." });
}
}
// Log error
// Return correct error notification
if (itemDisplaySetting == ItemDisplaySetting.Hide)
HidePathwayStep(ref e);
else
{
try
{
var step = pwStep.Fetch(sessionHandler, Int32.Parse(hfObjectID.Value));
}
catch (Exception ex)
{
ErrorUtilities.LogException(ex);
lblReferenceDescription.Text = string.Format("{0}{1}", " Message: ", ex.Message);
}
}
When to catch
Applying exceptions are usually done for the following cases:
- Logging of error and returning an error page/message:
- Action called by user
- Operation required for all following processes where normal
NULL
or content checks may not be sufficient.
- Logging of error, setting error message/property and continuing with next process