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