Jurudocs
Jurudocs

Reputation: 9185

How to deal with error handling in object literals?

How can I do some error handling within an object literal?
At least I wanted it to work like this :

window.App={
  Variables:{
    "views_data":
      try{
        json_parse(Drupal.settings.royal)
      }
      catch(e){
        JSON.parse(Drupal.settings.royal)
      }        
  }
}

Upvotes: 2

Views: 108

Answers (3)

LetterEh
LetterEh

Reputation: 26706

1) use an Immediately-Invoked Function Expression

views_data : (function () {
    var result = "",
        json = Drupal.settings.royal;

    try { result = json_parse(json); }
    catch (e) { result = JSON.parse(json); }
    return result;
}())

2) Unless there's something special about your json_parse, I'd actually recommend doing this the other way around -- using the browser's JSON.parse, instead. The native implementation is going to be faster than pretty much anything that you could write yourself. Then fall back to handwritten solutions, if JSON doesn't exist. Of course, that's if you aren't doing anything special in your implementation.

Upvotes: 1

Fabian Lauer
Fabian Lauer

Reputation: 511

As try{...}catch(err){...} is a control structure, you can not add it to an object literal in javascript. Depending on where you would like to store Drupal.settings.royal, you could write your object like this:

window.App = {
    Variables: {
        views_data: null    // this is optional
    }
};

Now as your object is ready´, you can try adding the parsed json to it:

try{
    window.App.Variables.views_data = json_parse(Drupal.settings.royal);
}catch(err){
    window.App.Variables.views_data = JSON.parse(Drupal.settings.royal);
}

Nice and clean.

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71939

You could use an immediately invoked function:

window.App = {
    Variables: {
        views_data: (function(){
            var data;
            try{
                data = json_parse(Drupal.settings.royal)
            }
            catch(e){
                data = {}
            }
            return data;
        }())
    }
}

Upvotes: 4

Related Questions