Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an exception object to a webservice

Following on from a question here got me thinking....

Would it/is it possible that when an application encounters an unhandled exception for this exception object to be serialized and sent to a web service with a db backend. Then, using a utility or even within Visual Studio the exception object could be loaded from the db and inspected??

Would this be at all possible? I guess the first question is whether you can serialize exception objects.

like image 715
Calanus Avatar asked Oct 15 '22 15:10

Calanus


2 Answers

You can serialize exception objects. This is in fact needed to transport an exception object from the server to the client, in the case of an exception being thrown in a web service call. This is why System.Exception has a constructor overload that creates an exception object from serialized data.

Code example for serializing / deserializing exception object:

private static void SerializeException(Exception ex, Stream stream)
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, ex);
}

private static Exception DeserializeException(Stream stream)
{
    BinaryFormatter formatter = new BinaryFormatter();
    return (Exception)formatter.Deserialize(stream);
}

// demo code
using (Stream memoryStream = new MemoryStream())
{
    try
    {
        throw new NullReferenceException();
    }
    catch (Exception ex)
    {
        // serialize exception object to stream
        SerializeException(ex, memoryStream);
        memoryStream.Position = 0;
    }
    // create exception object from stream, and print details to the console
    Console.WriteLine(DeserializeException(memoryStream).ToString());
}

That being said, I would probably settle for logging the exception type, message and stack trace somewhere so that I can examine the information.

like image 58
Fredrik Mörk Avatar answered Oct 18 '22 08:10

Fredrik Mörk


Using WCF, this would be an easy task. Implement a custom IErrorHandler to send errors to a logging service. The FaultException<TDetail> class is used by WCF to report errors in a SOAP XML format and it could be sent directly to the logging service.

like image 22
Ray Vernagus Avatar answered Oct 18 '22 08:10

Ray Vernagus