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.
我正在使用在我的ASP.net应用程序中捕获global.asax中的错误的常见做法。在global.asax中,我有一个函数Application_Error,它将错误记录到数据库中。
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.
但是,当从客户端调用的异步方法(使用[WebMethod]属性修饰的方法)抛出异常时,这没有任何帮助。异常只是冒泡并且可能会返回到客户端代码,但我希望自动在服务器上运行错误处理代码,类似于在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.
我该如何做到这一点?一种方法是使用try-catch包装每个异步方法,但这对我来说似乎不是一个好的解决方案。
2 个解决方案
#1
0
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:
一种选择是创建一个ASP.NET输出过滤器,拦截并记录ASP.NET发送给客户端的WebMethod异常。这是基本的想法:
- Create a subclass of Stream that captures the content of the response.
- 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. - In Global.Application_PostMapRequestHandler, install an instance of this class as the output filter for JSON requests.
创建Stream的子类,捕获响应的内容。
当流关闭时,检查响应是否具有500状态代码以及“jsonerror:true”标头。如果是,则响应包含WebMethod异常;记录异常。
在Global.Application_PostMapRequestHandler中,安装此类的实例作为JSON请求的输出过滤器。
For complete source code, see this * answer.
有关完整的源代码,请参阅此*答案。
#1
0
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:
一种选择是创建一个ASP.NET输出过滤器,拦截并记录ASP.NET发送给客户端的WebMethod异常。这是基本的想法:
- Create a subclass of Stream that captures the content of the response.
- 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. - In Global.Application_PostMapRequestHandler, install an instance of this class as the output filter for JSON requests.
创建Stream的子类,捕获响应的内容。
当流关闭时,检查响应是否具有500状态代码以及“jsonerror:true”标头。如果是,则响应包含WebMethod异常;记录异常。
在Global.Application_PostMapRequestHandler中,安装此类的实例作为JSON请求的输出过滤器。
For complete source code, see this * answer.
有关完整的源代码,请参阅此*答案。