0

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...

4
  • You have to use typescript to explicitly tell the function could throw an error. Commented May 28, 2022 at 12:47
  • 2
    @SajeebAhamed - I don't see how TypeScript helps in this case...? This isn't a type assertion function. Commented May 28, 2022 at 12:47
  • 1
    There is hardly any code that can't throw. Additionally, what would you do, if this threw? What should the error handler do? If it was a normal case, why throw in the first place, and not return a value, when it's expected to get handled? Don't produce vexing exceptions. Commented May 28, 2022 at 12:47
  • Thank you so much, but I'm actually writing TypeScript. Commented May 28, 2022 at 12:50

1 Answer 1

4

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 tag on the question. The above still works for TypeScript, but you'd provide the type annotation for the parameter in a different place (and it's probably better not to use string for the parameter name, since that's a type name [it works, but it's confusing]):

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

    return parseInt(str, 16);
};

Playground link

Here's a screenshot from the TypeScript playground showing how a decent IDE will show that function if you hover the mouse over it (or similar):

IDE showing the JSDoc annotations for the function in a popup

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, and yes, I was exactly expecting something like Java or Swift like IDE support that tells us the function would throw.
And I've just tried JSDoc, and it works. I'm so happy to see your answer.
@Shin-00 - Glad that helped! I'd messed up the annotations a bit, I've just fixed them. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.