Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
How to make functions explicit that it would throw an Error in JavaScript?

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
};

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda