14

I'm using the [System.Web.Script.Services.ScriptService] tag to use web services callable from client side javascript. What I need is a way of globally logging any unhandled exceptions in those methods. On the client side, I get the error callback and can proceed from there, but I need a server-side catch to log the exception.

The guy at this url: http://ayende.com/Blog/archive/2008/01/06/ASP.Net-Ajax-Error-Handling-and-WTF.aspx

suggests that this can't be done.

Is that accurate? Do I seriously have to go to every single webmethod in the entire system and try/catch the method as a whole.

4 Answers 4

15

You can use an HTTP module to capture the exception message, stack trace and exception type that is thrown by the web service method.

First some background...

  • If a web service method throws an exception the HTTP response has a status code of 500.

  • If custom errors are off then the web service will return the exception message and stack trace to the client as JSON. For example:
    {"Message":"Exception message","StackTrace":" at WebApplication.HelloService.HelloWorld() in C:\Projects\Stackoverflow Examples\WebApplication\WebApplication\HelloService.asmx.cs:line 22","ExceptionType":"System.ApplicationException"}

  • When custom errors are on then the web service returns a default message to the client and removes the stack trace and exception type:
    {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}

So what we need to do is set custom errors off for the web service and plug in an HTTP module that:

  1. Checks if the request is for a web service method
  2. Checks if an exception was thrown - that is, a status code of 500 is being returned
  3. If 1) and 2) are true then get the original JSON that would be sent to the client and replace it with the default JSON

The code below is an example of an HTTP module that does this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;

public class ErrorHandlerModule : IHttpModule {

  public void Init(HttpApplication context) {
    context.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
    context.EndRequest += OnEndRequest;
  }

  static void OnPostRequestHandlerExecute(object sender, EventArgs e) {
    HttpApplication context = (HttpApplication) sender;
    // TODO: Update with the correct check for your application
    if (context.Request.Path.StartsWith("/HelloService.asmx") 
        && context.Response.StatusCode == 500) {
      context.Response.Filter = 
        new ErrorHandlerFilter(context.Response.Filter);
      context.EndRequest += OnEndRequest;
    }
  }

  static void OnEndRequest(object sender, EventArgs e) {
    HttpApplication context = (HttpApplication) sender;
    ErrorHandlerFilter errorHandlerFilter = 
      context.Response.Filter as ErrorHandlerFilter;
    if (errorHandlerFilter == null) {
      return;
    }

    string originalContent =
      Encoding.UTF8.GetString(
        errorHandlerFilter.OriginalBytesWritten.ToArray());

    // If customErrors are Off then originalContent will contain JSON with
    // the original exception message, stack trace and exception type.

    // TODO: log the exception
  }

  public void Dispose() { }
}

This module uses the following filter to override the content sent to the client and to store the original bytes (which contain the exception message, stack trace and exception type):

public class ErrorHandlerFilter : Stream {

  private readonly Stream _responseFilter;

  public List OriginalBytesWritten { get; private set; }

  private const string Content = 
    "{\"Message\":\"There was an error processing the request.\"" +
    ",\"StackTrace\":\"\",\"ExceptionType\":\"\"}";

  public ErrorHandlerFilter(Stream responseFilter) {
    _responseFilter = responseFilter;
    OriginalBytesWritten = new List();
  }

  public override void Flush() {
    byte[] bytes = Encoding.UTF8.GetBytes(Content);
    _responseFilter.Write(bytes, 0, bytes.Length);
    _responseFilter.Flush();
  }

  public override long Seek(long offset, SeekOrigin origin) {
    return _responseFilter.Seek(offset, origin);
  }

  public override void SetLength(long value) {
    _responseFilter.SetLength(value);
  }

  public override int Read(byte[] buffer, int offset, int count) {
    return _responseFilter.Read(buffer, offset, count);
  }

  public override void Write(byte[] buffer, int offset, int count) {
    for (int i = offset; i < offset + count; i++) {
      OriginalBytesWritten.Add(buffer[i]);
    }
  }

  public override bool CanRead {
    get { return _responseFilter.CanRead; }
  }

  public override bool CanSeek {
    get { return _responseFilter.CanSeek; }
  }

  public override bool CanWrite {
    get { return _responseFilter.CanWrite; }
  }

  public override long Length {
    get { return _responseFilter.Length; }
  }

  public override long Position {
    get { return _responseFilter.Position; }
    set { _responseFilter.Position = value; }
  }
}

This method requires custom errors to be switched off for the web services. You would probably want to keep custom errors on for the rest of the application so the web services should be placed in a sub directory. Custom errors can be switched off in that directory only using a web.config that overrides the parent setting.

2
  • Although I'm not following through with this on my current project, this probably is the only way to reliably catch all these errors.
    – Clyde
    Feb 19, 2009 at 17:45
  • I tried this one, but somehow my context.Response.Filter.length threw an exception of type 'System.NotSupportedException'. It just doesn't work. I think it is very close, my output is exactly like you said. and I got 500 status code.
    – maxisam
    Sep 6, 2013 at 21:15
3

You run the Stored Procedure in the backend. Then, for a single variable, it returns more than 1 value. Because of that, a conflicts occurs, and, this error is thrown.

1

I know this doesn't answer the question per-say, but I went on my own quest a while back to find this out and would up empty handed. Ended up wrapping each web service call in a try/catch, and the catch calls our error logger. Sucks, but it works.

-1

In ASP.Net it is possible to catch all run handled exceptions using a global error handler although the blog post suggest this would not work but you could experiment with this approach trying to rethrow the error in some way?

Another idea would be to look at the open source elmah (Error Logging Modules and Handlers) for ASP.Net that might help or someone in that community may have an idea.

4
  • 1
    Yeah, I'm not sure you really understood the problem. The exception is caught by the ASP.NET script service code -- caught before I have a chance to catch it. So the global error handler doesn't work. The framework sends an error client-side so I can display a message, but there's no server hook
    – Clyde
    Jan 24, 2009 at 15:35
  • However, the elmah link is interesting...I will be sure to check that out
    – Clyde
    Jan 24, 2009 at 15:36
  • I'd second ELMAH. I use that for exactly this purpose myself.
    – Dave Ward
    Feb 17, 2009 at 3:33
  • ELMAH doesn't work as it uses the global error handler that the [ScriptServer] attribute suppresses.
    – WiseGuyEh
    Jan 23, 2013 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.