无法在ActionResult中捕获异常

时间:2019-07-18 18:42:16

标签: c# asp.net-mvc

嗨,我正在尝试在Action Controller中捕获异常,我想在输出和模态中显示异常,在两种情况下都无法使用

方法:

[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);
 }

断点显示消息在那里

enter image description here

然后什么也没发生,这关系到我的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');
   }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

return Json()基本上意味着您实际上以200状态代码进行响应。这意味着您的success代码将实际执行。

如果您希望调用error函数,那么您的请求应该会失败(4xx或5xx状态代码)。

可能的解决方法:

success: function (response) {
        if(response.error){
           //do stuffs
           return;
        }
        $.unblockUI();
        departmentPostSuccess();
        $('#departmentTable').DataTable().ajax.reload();
    }

答案 1 :(得分:1)

您可以通过变量传递操作结果,以响应成功, 然后在javascript中检查成功,如果成功为true,则显示成功消息,否则显示错误消息

success: function (response) {
        if (response.success) {
             $.unblockUI();
             departmentPostSuccess();
             $('#departmentTable').DataTable().ajax.reload();
        } else {
           $.unblockUI();
           $('#errorModalmsg').text(response.error);
           $('#errorModal').modal('show');
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }
 catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        return Json(new { success=false, error = ex.Message });
    }
     return Json(new { success=true});

答案 2 :(得分:1)

正如其他人指出的那样,返回Json本质上将返回200 OK响应。您需要返回某种错误。

就个人而言,除非您计划在捕获中添加某种日志记录或执行某种逻辑,否则我将避免捕获此通用异常。但是,如果您想保持成功,我会在将异常消息记录到控制台后直接抛出异常:

catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
    throw ex;
}