从try..catch返回的优雅方式



返回null的优雅方式。不希望返回两次

选项1:

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

选项2:

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

选项3:如果我们选择了这个选项,我们为什么要这样做?

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

为什么我需要这样做?

如果我试图获得window.sessionStorage,我会得到DOMException,因此我需要使用try...catch

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

原始代码:

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

这可真奇怪。7个月没反应?我自己也在寻找类似的东西,但找不到一个雄辩的解决方案。我创造了我自己的


编辑经过进一步的工作,我发现null安全操作符确实在JS中存在!耶!下面的函数仍然非常有用,也许现在更有用了,因为可以使用安全操作符获得所需的精确值,然后正确处理它。


考虑使用类似的函数:

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

这可能不完全符合您的需求,但您可以按照自己的意愿创建函数。这将使您的重要业务或UI逻辑保持混乱,因此您和其他人可以专注于重要的内容。

示例用法(如果已知帐户有一个期望值):

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

null safety:

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

我希望你和其他人觉得这有用,或者更好的是,分享一个更好的方法来处理这个问题。我希望c#的null安全检查操作符能够在JS中使用,但是没有运气(例如,"account?.license?)licenseType ? ?"任何事")

最新更新