Chaining "Run JS Code" queries and error handling

  • Goal: I am calling one "Run JS Code" query from another "Run JS Code" query and would like to know if there was in error when calling the first query

I found this thread (How to force javascript query to fail? - #5 by bradlymathews) where another user near the end of the thread encounters the same issue, and the retool team responds in Jan 2023 saying this was fixed, but I still can't figure out how to propagate the error.

  • Steps:
//fooQuery "Run JS Code"
console.log("fooQuery called")
return Promise.reject("foo error");
//barQuery "Run JS Code"
console.log("barQuery started")
let results = await fooQuery.trigger()
console.log("fooQuery results:")
console.log(results) 
// results is undefined
// I would like to know whether the fooQuery call succeeded or not here

debug console looks like this

I do see in the thread linked above that this was mentioned as bad workaround

This is a bad workaround:
return {error: 'some error text'}

I can work with this if it's the only way, but would prefer a better solution if one exists.

I have tried catching the error as well with no success.

//barQuery implementation with try-catch
async function fetchData() {
  try {
    const response = await fooQuery.trigger()
    console.log("fooQuery results:")
    console.log(response);
  } catch (error) {
    console.error('Error:', error);
  }
}
fetchData();
//barQuery implementation with Promise error catching
async function fetchData2() {
    const response = await fooQuery.trigger()
    console.log("fooQuery results:")
    console.log(response);
}

fetchData2().catch((error) => {
  console.error('Error:', error);
});

For both implementations shown above, the "fooQuery results:" log still will get executed, and I don't see an "Error: ..." log.

Hello!

I think you can handle the errors directly in the Event Handlers of the JS Query and have it run a script/trigger what to do on an error. You can also just await the fooQuery.trigger and then use a ternary chain to return the data or error as needed:

If I adjust the fooQuery to return Promise.all instead of Promise.reject:

ETA: I noticed an odd thing when switching between fooQuery return values... The first run of the barQuery script produced a null return but then subsequent calls worked as intended. This is probably a promise/async thing that I didn't resolve properly in hasty sample setup.

1 Like

Thank you @pyrrho, what you suggested works (though interesting that it is a different pattern than triggering resource queries where the trigger() returns the actual result value)

Noticed this as well, but I can live with this.

The first run of the barQuery script produced a null return but then subsequent calls worked as intended.