如何捕获 global.asax 中的 AJAX WebMethod 错误?

发布于 2024-11-17 12:31:22 字数 354 浏览 8 评论 0原文

我正在使用在 ASP.net 应用程序中捕获 global.asax 中的错误的常见做法。在 global.asax 中,我有一个函数 Application_Error 将错误记录到数据库中。

这对于记录用户请求页面时发生的错误非常有效。

但是,当从客户端调用的异步方法(用 [WebMethod] 属性修饰的方法)抛出异常时,这没有任何帮助。异常只是冒泡,可能会返回到客户端代码,但我希望错误处理代码在服务器上自动运行,类似于在 global.asax 中记录页面错误的方式。

我该如何实现这个目标?一种方法是用 try-catch 包装每个异步方法,但这对我来说似乎不是一个好的解决方案。

I'm using the common practice of catching errors in global.asax in my ASP.net application. In global.asax, I have a function Application_Error that logs the errors to the database.

This works very well to log errors that occur when the user requests a page.

However, this does nothing to help when an asynchronous method (a method decorated with the [WebMethod] attribute) called from the client-side throws an exception. The exception simply bubbles up and may be returned to the client-side code, but I would like to have the error handling code run on the server automatically similar to how page errors are logged in global.asax.

How do I accomplish this? One way would be to wrap every single asynchronous method with try-catch, but this doesn't seem like a good solution to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事与诗 2024-11-24 12:31:22

一种选择是创建 ASP.NET 输出过滤器,拦截并记录 ASP.NET 发送到客户端的 WebMethod 异常。基本思想如下:

  1. 创建 Stream 的子类来捕获响应的内容。
  2. 当流关闭时,检查响应是否具有 500 状态代码以及 "jsonerror: true" 标头。如果是,则响应包含 WebMethod 异常;记录异常。
  3. 在 Global.Application_PostMapRequestHandler 中,安装此类的实例作为 JSON 请求的输出过滤器。

有关完整的源代码,请参阅此 StackOverflow 答案

One option is to create an ASP.NET output filter that intercepts and logs WebMethod exceptions sent by ASP.NET to the client. Here's the basic idea:

  1. Create a subclass of Stream that captures the content of the response.
  2. When the stream is closed, check whether the response has a 500 status code as well as a "jsonerror: true" header. If so, the response contains a WebMethod exception; log the exception.
  3. In Global.Application_PostMapRequestHandler, install an instance of this class as the output filter for JSON requests.

For complete source code, see this StackOverflow answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文