catch (err) -> err.message

Post Reply
User avatar
foxpalace
Member
Posts: 33
Joined: Fri Jan 14, 2011 12:25 pm
Location: Germany

catch (err) -> err.message

Post by foxpalace »

Hi,

i have this code from documentation:

Code: Select all

    try 
    {
    dosomething
    }
    catch (err) 
    {
        job.fail('PDF error: %1');
        //job.fail('PDF error: %1', [err]); //grmpf err unknown
    }
why do I get this error, when I use the line whit [err]?

Code: Select all

michael@macpro seitenmelder % SwitchScriptTool --transpile .
Error: Failed to transpile the code: TypeScript failed with exit code 2
Error: TypeScript standard output: main.ts(36,42): error TS2322: Type 'unknown' is not assignable to type 'string | number | boolean'.
I tried with err.message too
freddyp
Advanced member
Posts: 1008
Joined: Thu Feb 09, 2012 3:53 pm

Re: catch (err) -> err.message

Post by freddyp »

It can sometimes happen that TypeScript does not know the type of a variable and then you get this error message. It is seems strange that this should be the case when catching an error, but that is correct because you can throw anything so TypeScript does not know the type of what will be thrown.

There are two possible approaches.

There is an option you can add to the compilerOptions in the tsconfig.json file in your script folder:
"useUnknownInCatchVariables": false
I will discuss internally if we want to add that for future versions of Switch. I am not sure we should.

The one that you can do immediately, and this is a general remark, is to give TypeScript some help and specify the type:

Code: Select all

try {
    dosomething
} catch (err) {
    job.fail('PDF error: %1', [(err as Error).message);
}
Another example is when there are overloads (more than 1 possible return type). flowElement.getPropertyStringValue for example can return string or string[] depending on whether the property is defined as single line or multiline. If you want to do something with the result as a string TypeScript will complain, and if you want to do something with the result as an array TypeScript will also complain. In this case (and in many/most? other cases) you will probably know what type is returned and then you can do this:

Code: Select all

let propValue = await flowElement.getPropertyStringValue("propTag") as string;
Casting a variable is of course also a possible approach to enforce a certain type:

Code: Select all

let propValue = (await flowElement.getPropertyStringValue("propTag")).toString();
but this will not always be possible.
Post Reply