spotfiresoftware / spotfire-mods

Spotfire® Mods
https://spotfiresoftware.github.io/spotfire-mods/
Other
54 stars 41 forks source link

error in Action Mods Docs/Snippets `getColumnOrThrow()` #148

Closed nikomaresco-csg closed 2 months ago

nikomaresco-csg commented 2 months ago

on the Snippets page, the example "Insert columns to an existing data table with custom column match" has a function getColumnOrThrow(), below:

https://spotfiresoftware.github.io/spotfire-mods/docs/action-mods/snippets/#insert-columns-to-an-existing-data-table-with-custom-column-match

function getColumnOrThrow(table: Spotfire.Dxp.Data.DataTable, columnName: string) {
    const col = table.Columns.Item.get(columnName);
    if (col == null) {
        throw new Error(`Cannot find column '${columnName}' in table '${table.Name}'.`);
    }
    return col;
}

but this null check is never executed, because if the column does not exist, the API throws the following error, halting the script:

Error: The column 'Zone' does not exist in the collection.
    at getColumnOrThrow (C:\Users\...\.js:22:40) ->     const col = table.Columns.Item.get(columnName);

to capture the error and maybe add more info, you could use:

    try {
        const col = table.Columns.Item.get(columnName)!;
        return col;
    } catch (e) {
        throw new Error(`Cannot find column '${columnName}' in table '${table.Name}'.`);
    }

however in this example you're forced to use the ! operator, which might not be desired.

are there any other scenarios in which table.Columns.Item.get(columnName) can return a null value?

handerss-spotfire commented 2 months ago

You are correct, the indexed property on a DataColumnCollection throws if a column with the name is missing. The proper way to write the function would be to use the TryGetValue API.

I have updated the snippet so it works as expected, thanks for pointing this out!