Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 856
Dhaval Jardosh Avatar asked Jun 28 '26 09:06

Dhaval Jardosh


1 Answers

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'")

like image 190
VeteranCoder Avatar answered Jun 29 '26 21:06

VeteranCoder