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

100
Visualizações
Elegant way to return from try...catch - Javascript

Elegant way to return null. Don't want to return it twice.

Option 1:

function readSessionStorage(key) {
    try {
        if (typeof window !== 'undefined') {
            return JSON.parse(window.sessionStorage.getItem(key));
        }
        return null;
    } catch {
        return null;
    }
}

Option 2:

function readSessionStorage(key) {
    try {
        return JSON.parse(window.sessionStorage.getItem(key));
    } catch {
        return null;
    }
}

Option 3: If we pick this option, why should we do this?

function readSessionStorage(key) {
    try {
        if (typeof window !== 'undefined') {
            return JSON.parse(window.sessionStorage.getItem(key));
        }
    } catch {}
    return null;
}

Why do I need to do this?

I'm getting DOMException if I try to get window.sessionStorage, and hence I need to use try...catch.

function readSessionStorage(key) {
    if (typeof window !== 'undefined' || !window.sessionStorage) {
        return JSON.parse(window.sessionStorage.getItem(key));
    }
    return null;
}

Original Code:

function readSessionStorage(key) {
    if (typeof window !== 'undefined') {
        return JSON.parse(window.sessionStorage.getItem(key));
    }
    return null;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Well, that's odd. No response in seven months? Well, I was looking for something like this myself, and couldn't find an eloquent solution. I created my own.


Edit: upon further work, I found that the null safety operators do exist in JS! Yay! The function below is still quite helpful, perhaps more so now since one can use the safety operator to get to the precise value desired, then handle it correctly.


Consider using a function similar to this:

const defineCheck = (item, defaultVal = '') => { 
    try {
        return (item !== null && item !== undefined) ? item : defaultVal;
    } catch {
        return defaultVal;
    }
}

This might not exactly fit your needs, but you can make your function however you want. This will keep the clutter out of your important business or UI logic, so you and others can focus on what is important.

Sample usage (if account is known to have an expected value):

tempForm.ExpirationDate = defineCheck(account.expirationDate);
tempForm.LicenseType = defineCheck(account.licenseType, 'Nada');

With null safety:

tempForm.ExpirationDate = defineCheck(account?.license?.expireDate);
tempForm.LicenseType = defineCheck(account?.license?.licenseType, 'Nada');

I hope you and others find this useful, or better yet, share a much better way to deal with this problem. I'd hoped the C# null safety check operator made its way to JS, but no luck (e.g., "account?.license?.licenseType ?? 'Nada'")

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