Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBScript / Classic ASP - How do I Check If a Property Exists in An Object Without Throwing an Error

Tags:

asp-classic

Sample Code:

Dim myObject
Set myObject = JSON.parse(someJsonResponseFromTheServer)    

myFunction(myObject.someProperty)

The Problem:

When code similiar to this is ran in my application, it throws a 500 error from the server with a message similar to "Object Does not support property or method 'someProperty'. What I would like to do to solve this problem is something like this:

Dim myObject
Set myObject = JSON.parse(someJsonResponseFromTheServer)    

If myObject.someProperty Then
    myFunction(myObject.someProperty)
End If

However, if I add the conditional, it throws the same error on the line with the conditional instead of the line with the method call.

My Question:

In ASP Classic, how do you detect if a property exists within an object without throwing an error?

like image 571
Levi Hackwith Avatar asked Apr 16 '12 01:04

Levi Hackwith


3 Answers

On the assumption that you are including some runat="server" js file that provides you with the JSON parser then JSON.parse is going to return a Javascript object.

If the above assumption is correct then the following ought to work:

If myObject.hasOwnProperty("someProperty") Then 
    myFunction(myObject.someProperty) 
End If 
like image 82
AnthonyWJones Avatar answered Nov 19 '22 12:11

AnthonyWJones


One of the benefits of classic ASP is that it allows you to run both VBScript and JScript in the same page - thus you can use the power of both.

First, add this block of JScript code to your existing .asp file:

<script language="JScript" runat="server">
function CheckProperty(obj, propName) {
    return (typeof obj[propName] != "undefined");
}
</script>

And assuming VBScript is the default language in the page, you can call it from within your VBScript code like this:

Dim myObject
Set myObject = JSON.parse(someJsonResponseFromTheServer)    
If CheckProperty(myObject, "someProperty") Then
    myFunction(myObject.someProperty)
End If

Tested it with generic class object and it works fine - the JScript is compiled before the VBScript thus accessible to it.

like image 38
Shadow Wizard Hates Omicron Avatar answered Nov 19 '22 14:11

Shadow Wizard Hates Omicron


Sadly, this usually means an 'on error' statement.

Private Function TestProperty()
    Dim Success
    Success = False

    On Error Resume Next
        ' set for property here
        Success = (Err.Number = 0)
    On Error Goto 0
    TestProperty = Success
Exit Function   
like image 7
Lynn Crumbling Avatar answered Nov 19 '22 13:11

Lynn Crumbling