Using fetch better handling if object doesnt exist

Using fetch throws an error if the object doesnt exist, is there a more graceful way to handle it, right now im doing a new query for .first() which if it doesnt exist will be undefined so i can continue (in a for loop)

Is there any difference under the hood between fetch and first ?

You could subclass fetch by:

class NewObject extends Parse.Object {
  safeFetch(...args) {
     try {
       return await this.fetch(...args);
     } catch (e) {
       if (e.code !== Parse.Error.OBJECT_NOT_FOUND) {
         throw e;
       }
    }
  }
}

Alternatively you could register a prototype method that can be used accross all Parse.Objects:

Parse.Object.prototype.safeFetch = function(...args) {
  try {
    return this.fetch(...args);
  } catch(e) {
    if (e.code !== Parse.Error.OBJECT_NOT_FOUND) {
      throw e;
    }
  }
}


const obj = new Parse.Object('ABC');
obj.id = "abc";
console.log(await obj.safeFetch());
1 Like

This is awesome, thank you, looking forward to trying it. Is this something which would be useful to be built into parse core though