Reputation: 288
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...
Upvotes: 0
Views: 2622
Reputation: 1074505
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 typescript 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);
};
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):
Upvotes: 4