Home > Net >  How to make functions explicit that it would throw an Error in JavaScript?
How to make functions explicit that it would throw an Error in JavaScript?

Time:05-28

I'd like to make my functions explicit that it would throw Errors.

For example;

const hexToDec = (string) => {
  if (!isHex(string)) {
    throw new Error("the given string is not hex.")
  }

  return parseInt(string, 16);
}

when I see this code on my IDE, it tells me that this code returns String, but no information about the possibility of Error. My team members might forget to "try - catch".

I have an idea that is to make this function async, so that it returns a Promise. However, I think this code should be synced...

CodePudding user response:

Within JavaScript itself, you can't, there's nothing like Java's concept of checked exceptions that you declare.

With JSDoc annotations, you can annotate the function to say it throws:

/**
 * Converts the given hex string to a number.
 *
 * @param {string} string The string to convert.
 * @returns {number} The resulting number.
 * @throws Error if `string` isn't valid hex.
 */
const hexToDec = (string) => {
    if (!isHex(string)) {
        throw new Error("the given string is not hex.");
    }

    return parseInt(string, 16);
};

My team members might forget to "try - catch".

In general, errors should be caught as far out as possible, typically in the entry point function from the environment (for instance, an event handler or host function callback). Your team members shouldn't need to wrap every call to hexToDec in try/catch — if they're unsure if the string contains valid hex, they can check it with isHex. Exceptions are for exceptional conditions, trying to convert the string when you expect it to be valid.

I have an idea that make this function async, so that it return a Promise. However, I think this code should be synced...

Making it async wouldn't do anything to make it necessary to check whether it fails. It would just mean that instead of throwing it would reject its promise (which is the async version of throwing).


I missed the IDE showing the JSDoc annotations for the function in a popup

  • Related