【发布时间】:2019-11-27 18:17:41
【问题描述】:
您好,我正在尝试在此动作控制器中捕获异常,我想在输出和模态中显示异常,这两种情况都不起作用
方法:
[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);
}
断点显示消息在那里
然后什么都没有发生,它进入了我的 ajax 调用的成功部分
error: function (e) {
$.unblockUI();
$('#errorModalmsg').text(e.responseJSON.error);
$('#errorModal').modal('show');
},
success: function () {
$.unblockUI();
departmentPostSuccess();
$('#departmentTable').DataTable().ajax.reload();
}
我错过了什么?
编辑:我更关心为什么 Diagnostics.Debug 没有捕捉到任何东西,我尝试了不同类型的错误
编辑 2 解决方案: 我关心的是将内部 .NET 异常带到视图中,所以我发现这样做here 最后我无法使 Diagnostics.Debug 输出工作
catch (Exception ex)
{
return new HttpStatusCodeResult(500, " :( Something bad happened: " + ex.Message);
}
Ajax,它也出现在浏览器控制台中
error: function (xhr, httpStatusMessage, customMessage) {
if (xhr.status === 500) {
$.unblockUI();
$('#errorModalMsg').text(customMessage);
$('#errorModal').modal('show');
}
}
【问题讨论】:
-
return Json(new { error = ex.Message });将是一个成功的 HTTP 状态代码。您的 ajax 代码不会将其检测为错误情况。
标签: c# asp.net-mvc