I have a situation where I use jQuery to call Webmethod in .aspx codebehind (not asmx webservice or anything similar). I have a simple error logger defined in Global.asax ApplicationError, so (almost) all exceptions are being caught and logged in a single place. The thing here is that ApplicationError method is not reached if an exception occurs inside a webmethod.
Here's a simple example:
Webmethod call:
$.ajax({
type: "POST",
url: "/MyMethods.aspx/MyMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert('ok');
}
});
Webmethod implementation:
Public Class MyMethods
Inherits System.Web.UI.Page
<System.Web.Services.WebMethod()> _
Public Shared Function MyMethod() As String
Throw New Exception("Forced.")
Return sb.ToString
End Function
End Class
And global.asax
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim filename As String = "d:\test.txt"
Using objWriter As New System.IO.StreamWriter(filename, True)
objWriter.WriteLine(Server.GetLastError().GetBaseException().Message)
End Using
End Sub
Is there any way to 'convince' ApplicationError method to be reached when webmethod throws an exception? I have tried (literally) hundreds of scenarios:
- ELMAH
- http://geekswithblogs.net/pavelka/archive/2005/09/05/HowToCreateAGlobalExceptionHandlerForAWebService.aspx
http://blog.theobjectguy.com/2009/12/exceptional-gotchas.html
lots questions here on SO...
...but none of them worked so far. So any help would be strongly appreciated!