最近我和同事讨论过,关于使用try
和catch
来通知错误或避免错误。try-catch是为了防止还是处理错误? (在javascript中)
这是我同事的做法:
import Config from 'config';
export const getUserFromLocalStorage =() => {
const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);
try {
return key ? JSON.parse(localStorage[key]) : {};
} catch (e) {
return {};
}
};
Wich means, he doesn't care about the given error and he is just carrying of returning an object in order to continue the process
和我的是:
import Config from 'config';
export const getUserFromLocalStorage =() => {
const key = Object.keys(localStorage).find(value => value === `${Config.applicationId}/currentUser`);
try {
return key ? JSON.parse(localStorage[key]) : {};
} catch (e) {
console.log('the given error', e); // Just simple notifier for this example
}
};
,但我的做法,仍然有一个问题,就是它会返回undefined
(这可能会崩溃内置我的应用程序),可以使用finally
轻松修复它并返回一个默认值,但对我来说听起来不太好。
问题
那么将使用try
catch
和finally
如果需要的话,使我的应用程序稳定的平衡。
我们的方法有什么问题吗?
特别是,我们不能信任来自localStorage
的数据,那么这个实现的最佳方法是什么?
'是它会返回未定义的(可能会导致内部应用程序崩溃)':您应该记录该方法可能会返回'undefined',并且您的代码调用它应该能够处理该问题。同样,你的同事的空对象可能会导致调用代码的异常。主要是记录在错误状态下返回的内容,并让呼叫者决定要做什么。 –
不,您不会使用'finally'来为错误情况返回默认值。 – Bergi
@Bergi'finally'的效用是什么 – JoseAPL