【问题标题】:Exception handling in ASP.NET (C#) web servicesASP.NET (C#) Web 服务中的异常处理
【发布时间】:2014-12-31 01:08:01
【问题描述】:

我正在寻找一种将我的 asp.net 应用程序的 Web 服务中的异常消息传输到 ajax 错误回调函数的方法。 我所能找到的只是将 Web 服务引发的异常捕获到 C# 代码中,但我是从 ajax 代码而不是 C# 代码调用我的服务。我想要的不仅仅是返回的 HTTP 状态代码。
这是我的服务代码的捕获块:

catch (Exception ex)
        {
            var fault = new GenericFault { Message = ex.Message, Operation = "" };
            throw new FaultException<GenericFault>(fault);
        }
    }

这是我的 ajax 错误回调:

 error: function (err) {
         alert("The server encountered an error, please resubmit your request. If the problem persists, contact your administrator.");
         return 'error occured';
    }

我已经尝试过抛出网络故障异常,但这也没有达到目的,因为只有 HTTP 状态代码被传递。

【问题讨论】:

  • 通常传递给Error回调的参数有很多属性,包括消息/堆栈跟踪/状态码/异常。究竟是什么问题?
  • 谢谢@Nunners 我得到的问题是 ia 抛出了错误异常,它不会更新错误回调的属性..更新了下面的答案

标签: c# asp.net ajax exception-handling


【解决方案1】:

找到了答案。诀窍在于抛出正确的异常。
由于回调错误函数中捕获的错误在 xhr 对象中查看详细信息。
所以你需要抛出 HttpException 传递它的状态代码和字符串消息。 catch 块应该类似于:

catch (Exception ex)
        {
             throw new HttpException(500, ex.Message);

          }

那么您的 ajax 回调将获得您从此处传递的 ex.message:

error: function (err) {
     alert("The Detailed server error is "+err.responseJSON.Message);
     return 'error occured';
}

【讨论】:

    猜你喜欢
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2010-10-21
    • 2014-06-12
    相关资源
    最近更新 更多