Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6843411
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T00:14:31+00:00 2026-05-27T00:14:31+00:00

I’d like to trap any unhandled exception thrown in an ASP.NET web service, but

  • 0

I’d like to trap any unhandled exception thrown in an ASP.NET web service, but nothing I’ve tried has worked so far.

First off, the HttpApplication.Error event doesn’t fire on web services, so that’s out..

The next approach was to implement a soap extension, and add it to web.config with:

<soapExtensionTypes>
   <add type="Foo" priority="1" group="0" />
</soapExtensionTypes>

However, this doesn’t work if you call the web method over JSON (which my web site does exclusively)..

My next idea would be to write my own HttpHandler for .asmx, which would hopefully derive from System.Web.Script.Services.ScriptHandlerFactory and do something smart. I haven’t tried this yet.

Is there an approach I’m missing? Thanks!

Mike

UPDATE:

I’ll summarize the possibly solutions here:

1) Upgrade to WCF which makes this whole thing much, much easier.

2) Since you cannot sub-class or override the RestHandler class, you would have to re-implement the whole thing as your own IHttpHandler or use reflection to manually call into its methods. Since the source to RestHandler is public and only about 500 lines long, making your own version might not be a huge amount of work but you’d then be responsible for maintaining it. I’m also unaware of any licensing restrictions involved with this code.

3) You can wrap your methods in try/catch blocks, or perhaps use LAMBDA expressions to make this code a bit cleaner. It would still require you to modify each method in your web service.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T00:14:31+00:00Added an answer on May 27, 2026 at 12:14 am

    As described in Capture all unhandled exceptions automatically with WebService there really is no good solution.

    The reason that you cannot capture the HttpApplication.Error etc has to do with how the RestHandler has been implemented by the good folks at Microsoft. Specifically, the RestHandler explicitly catches (handles) the exception and writes out the exception details to the Response:

    internal static void ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)
    {
        try
        {
            NamedPermissionSet namedPermissionSet = HttpRuntime.NamedPermissionSet;
            if (namedPermissionSet != null)
            {
                namedPermissionSet.PermitOnly();
            }
            IDictionary<string, object> rawParams = GetRawParams(methodData, context);
            InvokeMethod(context, methodData, rawParams);
        }
        catch (Exception exception)
        {
            WriteExceptionJsonString(context, exception);
        }
    }
    

    To make matters worse, there is no clean extension point (that I could find) where you can change/extend the behavior. If you want to go down the path of writing your own IHttpHandler, I believe you will pretty much have to re-implement the RestHandler (or RestHandlerWithSession); regardless Reflector will be your friend.

    For those that may choose to modify their WebMethods

    If you are using Visual Studio 2008 or later, using Lambda expressions makes things not too bad (although not global/generic solution) in terms or removing duplicated code.

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public String GetServerTime()
    {
      return Execute(() => DateTime.Now.ToString());
    }
    
    public T Execute<T>(Func<T> action)
    {
      if (action == null)
        throw new ArgumentNullException("action");
    
      try
      {
        return action.Invoke();
      }
      catch (Exception ex)
      {
        throw; // Do meaningful error handling/logging...
      }
    }
    

    Where Execute can be implemented in a subclass of WebService or as an extension method.

    UPDATE: Reflection Evil

    As mentioned in my origional answer, you can abuse reflection to get what you want… specifically you can create your own HttpHandler that makes use of the internals of the RestHandler to provide an interception point for capturing exception details. I have include an “unsafe” code example below to get you started.

    Personally, I would NOT use this code; but it works.

    namespace WebHackery
    {
      public class AjaxServiceHandler : IHttpHandler
      {
        private readonly Type _restHandlerType;
        private readonly MethodInfo _createHandler;
        private readonly MethodInfo _getRawParams;
        private readonly MethodInfo _invokeMethod;
        private readonly MethodInfo _writeExceptionJsonString;
        private readonly FieldInfo _webServiceMethodData;
    
        public AjaxServiceHandler()
        {
          _restHandlerType = typeof(ScriptMethodAttribute).Assembly.GetType("System.Web.Script.Services.RestHandler");
    
          _createHandler = _restHandlerType.GetMethod("CreateHandler", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(HttpContext) }, null);
          _getRawParams = _restHandlerType.GetMethod("GetRawParams", BindingFlags.NonPublic | BindingFlags.Static);
          _invokeMethod = _restHandlerType.GetMethod("InvokeMethod", BindingFlags.NonPublic | BindingFlags.Static);
          _writeExceptionJsonString = _restHandlerType.GetMethod("WriteExceptionJsonString", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(HttpContext), typeof(Exception) }, null);
    
          _webServiceMethodData = _restHandlerType.GetField("_webServiceMethodData", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField);
        }
    
        public bool IsReusable
        {
          get { return true; }
        }
    
        public void ProcessRequest(HttpContext context)
        {
          var restHandler = _createHandler.Invoke(null, new Object[] { context });
          var methodData = _webServiceMethodData.GetValue(restHandler);
          var rawParams = _getRawParams.Invoke(null, new[] { methodData, context });
    
          try
          {
            _invokeMethod.Invoke(null, new[] { context, methodData, rawParams });
          }
          catch (Exception ex)
          {
            while (ex is TargetInvocationException)
              ex = ex.InnerException;
    
            // Insert Custom Error Handling HERE...
    
            _writeExceptionJsonString.Invoke(null, new Object[] { context, ex});
          }
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.