Globally log exceptions from ASP.NET [ScriptService] services Globally log exceptions from ASP.NET [ScriptService] services asp.net asp.net

Globally log exceptions from ASP.NET [ScriptService] services


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 webservice will return the exceptionmessage and stack trace to the clientas JSON. For example:
    {"Message":"Exceptionmessage","StackTrace":" atWebApplication.HelloService.HelloWorld()in C:\Projects\StackoverflowExamples\WebApplication\WebApplication\HelloService.asmx.cs:line22","ExceptionType":"System.ApplicationException"}

  • When custom errors are on then theweb service returns a default messageto the client and removes the stacktrace 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.


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.


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.