try {
// do some logic here.
} catch(ex) {
handleException();
throw exception;
}
复制代码
不是。应该尽量少。缘由以下:javascript
常见的错误:java
try {
// some logic
} catch(ex) {
console.log(ex);
}
复制代码
try {
// some logic
} catch(ex) {
throw new Error('There is some error occurs!');
}
复制代码
try {
// some logic
} catch(ex) {
throw ex;
}
复制代码
function isJsonString(str) {
try {
JSON.parse(str);
return true;
} catch() {
return false;
}
}
复制代码
function loadUser(id) {
try {
await userModel.get(id);
} catch(ex) {
throw new UnauthorizedError(`${}`); // (不太贴切,有没有更好的腻子)
}
}
复制代码
function loadUser(id, email) {
try {
await userModel.getById(id);
} catch(ex) {
await userModel.getByEmail(email);
}
}
复制代码
勇敢的 throw exception, 谨慎的 catch exception. 在方法设计中,应该尽量用 throw 替代状态返回值。bash
// return true is saved return false if not saved
function saveUser(user) {
// save user to database
}
复制代码
True 和 False 是没法预见全部状况的,若是 return false, 咱们没法知道到底出了什么错。 Catch exception not saved. No exception saved. 这样你也能够只关心正确的逻辑,若是没有 save 成功自动跳出。app
最大的问题,JS 是异步的。异步
try {
setTimeout(()=> {
throw new Error('Can you catch me?');
}, 0);
} catch(ex) {
// catch 不到
}
复制代码
function loadUser(id) {
try {
userModel.get(id);
} catch(ex) {
// catch 不到
}
}
复制代码
try {
users.forEach(async (user) => {
await userModel.save(user);
});
} catch(ex) {
// catch 不到
}
复制代码
总结成一句话就是:全部的异步操做都须要 await 之后才能 try catch。除非你知道,本身在作什么。async