Should try catch TypeScript assertion function?

Viewed 52

I create a TS assertion function, Later, I use it before passing the request DTO to the API service in a UI event handler.

function assertIsGetCampaignPackageReqDTO(
  value: any,
): asserts value is GetCampaignPackageRuquestDTO {
  if (!value.campaignId || !value.packageCode) {
    throw new Error('campaignId or packageCode is empty!');
  }
}

const onSearchFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  try {
    assertIsGetCampaignPackageReqDTO(searchCondition);
    const { value } = await getCampaignPackageQuery.execute(searchCondition);
    if (value?.code === '0') {
      setCampaignPackages(campaignPackages.concat(value.result));
    }
  } catch (error) {
    message.error(error.message);
  }
};

Should I use try...catch statement with the assertion function and show the error message to users? Or, I should validate the legality(if statement) of the request DTO before using the assertion function. The assertion function is only used for passing the TSC check?

Or this:

function assertIsGetCampaignPackageReqDTO(
  value: any,
): asserts value is GetCampaignPackageRuquestDTO {
  if (!value.campaignId || !value.packageCode) {
    throw new Error('value is not GetCampaignPackageRuquestDTO');
  }
}

const onSearchFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  if (!searchCondition.campaignId || !searchCondition.packageCode) {
    return message.error('campaignId or packageCode is empty!');
  }
  assertIsGetCampaignPackageReqDTO(searchCondition);
  const { value } = await getCampaignPackageQuery.execute(searchCondition);
  if (value?.code === '0') {
    setCampaignPackages(campaignPackages.concat(value.result));
  }
};
1 Answers

I assume all you want is to catch exceptions instead of letting your program be crashed.

  • If the code in function assertIsGetCampaignPackageReqDTO is exactly the same as in if condition, then you should choose one of those methods. I prefer using if condition for simplicity.
  • If there are other checks in assert function, you should use both: try catch and if condition. Using if if you want to catch separate cases such as campaignId and packageCode (as shown in your code). And using try catch to catch other failure cases.
if (!searchCondition.campaignId || !searchCondition.packageCode) {
    return message.error('campaignId or packageCode is empty!');
}

try {
    assertIsGetCampaignPackageReqDTO(searchCondition);
    const { value } = await getCampaignPackageQuery.execute(searchCondition);
    if (value?.code === '0') {
      setCampaignPackages(campaignPackages.concat(value.result));
    }
} catch (error) {
    message.error(error.message);
}

Related