11

I have a custom exception class as follows:

<Serializable>
Public Class SamException
    Inherits Exception
    Public Sub New()
        ' Add other code for custom properties here.
    End Sub
    Public Property OfferBugSend As Boolean = True

    Public Sub New(ByVal message As String)
        MyBase.New(message)
        ' Add other code for custom properties here.
    End Sub

    Public Sub New(ByVal message As String, ByVal inner As Exception)
        MyBase.New(message, inner)
        ' Add other code for custom properties here.
    End Sub

End Class

I'm using this for certain cases in returns from AJAX responses.

In the error function of my AJAX response I am determining that the error is of my custom type like this:

.... 
ajax code....
.error = function (xhr, text, message) {
    var parsed = JSON.parse(xhr.responseText);
    var isSamCustomError = (parsed.ExceptionType).toLowerCase().indexOf('samexception') >= 0;
 .... etc....

This allows me to post back a specific response to the client if the error is of my custom type.

BUT... I can't seem to get it to post out the extra property OfferBugSend to the client for the AJAX code to handle this case differently.

console.log("OfferBugSend: " + parsed.OfferBugSend) 

is showing undefined, and if I check the response, this is because xhr.responseText only contains the properties:

ExceptionType
Message
StackTrace

These properties are from the base class Exception but it is not passing my custom class properties...

How can I make that happen?

Jamie Hartnoll
  • 7,231
  • 13
  • 58
  • 97
  • 1
    Please attach a code example how you submit your AJAX and throw your `SamException`. – codeDom Oct 04 '17 at 08:41
  • I would advise try catch the code you want. If you hit your exception, throw that exception up from the BLL/DAL into your Presentation layer. In your presentation layer, provide a way to Return the New exception type that will be converted FROM your exception. Example is, try catch (special exception){ return new {.SpecialMessage="IamError",.IsError=True}. In your Ajax, check for IsError. –  Oct 10 '17 at 15:08

1 Answers1

3

The Exception class is serializable, but it contains an IDictionary and implements ISerializable, which requires a little more work for serializing your custom Exception Class.

The easier way to deal with this is by leveraging the Data collection of the Exception class like so:

Public Property OfferBugSend As Boolean
    Get
        Return Data("OfferBugSend")
    End Get
    Set(value As Boolean)
        Data("OfferBugSend") = value
    End Set
End Property

Another way to do this is to ensure your derived class also implements the ISerializable interface, which involves providing a serialization constructor and overriding GetObjectData(). See this other answer (in C#) as a baseline for that approach.

NoAlias
  • 9,218
  • 2
  • 27
  • 46