【问题标题】:MVC5 - return custom error doesn't workMVC5 - 返回自定义错误不起作用
【发布时间】:2018-06-25 21:17:00
【问题描述】:

MVC5,c#.net

View 对 MyAction() 进行 ajax 调用。 如果返回的错误具有以下“错误”部分:

error: function (request, status, errorThrown) {

         alert(errorThrown);  // Shows "Internal Server Error" instead of custom error               
        }

在控制器中:

 [HttpPost]
    public async Task<ActionResult> MyAction(string jsonParams)
    {
       try
       {
          ....
           // 'service' is written by another group in our company
           MyClass myObj= await service.myFunction(); // generates exception
          ....
       }
       catch (Exception ex)
        {
             // debugger Does stop here on the break point
             // so it does get here
             return new HttpStatusCodeResult(400, "My Custom error text");              

        }    

}

我认为在我使用“任务”之前它有效。 在这种情况下如何显示自定义错误文本?

非常感谢

【问题讨论】:

  • 使用您的浏览器工具(网络选项卡)检查将包含错误详细信息的响应(在您的方法中的代码执行之前可能会引发异常)
  • 它对我来说很好用。您能否发布您的完整代码,您的代码可能在其他地方存在问题。
  • 感谢您的回复。我确实在我的帖子中添加了一些代码点。 VS 调试器确实会在产生异常的那一行停止,然后立即去捕获;并在 HttpStatusCodeResult 行上停止。

标签: asp.net-mvc asp.net-mvc-5


【解决方案1】:

ajax 调用时设置 async true

 $.ajax({
    type: "POST",
    url: "/test/test2",
    data: postData,
    async: true
 });

【讨论】:

  • Ajax 默认是异步的 (true),所以这样做真的没有意义。
  • Yes "默认情况下,所有请求都是异步发送的(即默认设置为true)。如果需要同步请求,请将此选项设置为false。"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多