Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add extra properties in Custom Exception to return to AJAX function

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?

like image 574
Jamie Hartnoll Avatar asked Sep 18 '17 12:09

Jamie Hartnoll


Video Answer


1 Answers

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.

like image 171
NoAlias Avatar answered Oct 14 '22 05:10

NoAlias