Hi I am trying to catch Exceptions inside this Action Controller, I want to show the exception in the Output and in a Modal, won't work in both scenarios
Method:
[HttpPost]
public ActionResult PostDepartment(Department DM)
{
try
{
if (DM.OperationType == "Save")
{
using (dbConn ef = new dbConn())
{
Department dept = new Department();
short Id = Convert.ToInt16(ef.Department.Max(field => (short?)field.DepartmentID) + 1 ?? 1);
dept.DepartmentID = Id;
dept.Name = DM.Name;
dept.GroupName = DM.GroupName;
dept.ModifiedDate = DateTime.Now;
ef.Department.Add(dept);
ef.SaveChanges();
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return Json(new { error = ex.Message });
}
return new HttpStatusCodeResult(201);
}
The breakpoint shows that the message is there
And then nothing happens, it goes to the success part of my ajax call
error: function (e) {
$.unblockUI();
$('#errorModalmsg').text(e.responseJSON.error);
$('#errorModal').modal('show');
},
success: function () {
$.unblockUI();
departmentPostSuccess();
$('#departmentTable').DataTable().ajax.reload();
}
What am I missing?
Edit: I am more concerned as to why Diagnostics.Debug isn't catching anything, I tried different type of errors
Edit 2 Solution: What I cared about was to bring the internal .NET Exception to the View so I found this way of doing so here in the end I couldn't make Diagnostics.Debug output work
catch (Exception ex)
{
return new HttpStatusCodeResult(500, " :( Something bad happened: " + ex.Message);
}
Ajax, it also shows up in the browser console
error: function (xhr, httpStatusMessage, customMessage) {
if (xhr.status === 500) {
$.unblockUI();
$('#errorModalMsg').text(customMessage);
$('#errorModal').modal('show');
}
}