0
votes

I updated today (after a couple of months) my package.json file with the latest package versions, I think the ones impacting this error are the ones in the subject of the question.

Some error handling blocks as the following one

try {
  // ...
} catch(err) {
  console.log(err.message);
}

stopped working due to TypeScript error 2571: Object is of type 'unknown'.

Nice! I just had to apply following simple change:

try {
  // ...
} catch(err) {
  console.log(err instanceof Error ? err.message : JSON.stringify(err));
}

not only my code started to work once again, but I feel my code is more resilient as well.

The problem comes when I try to handle an error thrown from the AWS SDK v3.

import { CloudWatchLogs, ResourceNotFoundException } from "@aws-sdk/client-cloudwatch-logs";

const cwl = new CloudWatchLogs({ region: "us-east-2" });

try {
  const logGroupName = "...";
  const logStreamName = "...";
  const { events } = await cwl.getLogEvents({ logGroupName, logStreamName });

  // ...
} catch(err) {
  if(! (err instanceof ResourceNotFoundException)) console.log(err);
}

In the simplified (I'm not handling pagination) above code sample I simply want to ignore the ResourceNotFoundException, but the err instanceof ResourceNotFoundException check doesn't compile since ResourceNotFoundException is an interface rather than a class.

I found this answer which seems could help me.

The question is: should I write an instanceOf\w+Exception function (sorry for the regexp) for each AWS exception I need to handle, or is there a common and reusable way (provided by AWS or not)?