如何捕获 global.asax 中的 AJAX WebMethod 错误?
我正在使用在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是创建 ASP.NET 输出过滤器,拦截并记录 ASP.NET 发送到客户端的 WebMethod 异常。基本思想如下:
"jsonerror: true"
标头。如果是,则响应包含 WebMethod 异常;记录异常。有关完整的源代码,请参阅此 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:
"jsonerror: true"
header. If so, the response contains a WebMethod exception; log the exception.For complete source code, see this StackOverflow answer.
如何为 Web 服务创建全局异常处理程序
How to create a global exception handler for a Web Service