250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 노드
- Django
- TypeError: this.boardRepository.createBoard is not a function
- westagram
- wecode
- 스코프
- nodeJS
- javascript
- 장고초기세팅
- JWT
- pm2
- django westagram
- 자바스크립트
- docker
- crud2
- OSI7계층
- Jest
- 트랜잭션
- 프로미스
- on_delete
- typescript
- 호이스팅
- CORS
- bcrypt
- manytomanyfield
- status code
- rebase
- async/await
- 실행 컨텍스트
- node
Archives
- Today
- Total
될때까지
((기업협업4)) 자바스크립트 try..catch와 에러 핸들링 본문
728x90
try...catch
- try{}안의 코드를 실행합니다.
- 에러가 없다면 try의 마지막 줄이 실행되고, catch{} 블록은 실행하지 않고 패스 넘어갑니다.
- 에러를 만났다면 try{}안의 코드 실행이 중단되고 catch(err){}로 넘어갑니다.
- 이 때 변수 err에 어떤 에러때문에 넘어왔는지 해당 에러 객체가 담깁니다.
- 에러가 발생하면 자바스크립트는 에러 내용이 담긴 객체를 생성하고, catch블록에 객체를 인수로서 전달합니다.
throw
- throw를 사용하면 에러를 발생시킬 수 있습니다.
- try..catch로 에러를 전달하면, 해당 에러에 대한 핸들링을 할 수 있습니다.
throw를 모르고 작성했던 코드
// 특정 유저 삭제하기
router.delete("/:userId", async (req, res, next) => {
try {
const sql = `select * from users where id = ${req.params.userId};`;
const [rows, fields] = await db.query(sql);
if (rows.length) {
const delete_sql = `delete FROM users where id=${req.params.userId};`;
await db.query(delete_sql);
return res.status(200).json({ mesaage: "deleted" });
} else {
return res.status(404).json({ message: "USER_NOT_FOUND" });
}
} catch (e) {
console.log(e.message);
}
});
rows에 담긴 객체가 없다면 else문의 코드가 실행됩니다. 이때 바로 return을 404 에러코드와 메세지로 처리했습니다.
throw를 적용한 코드
// 특정 유저 삭제하기
router.delete("/:userId", async (req, res, next) => {
try {
const sql = `select * from users where id = ${req.params.userId};`;
const [rows, fields] = await db.query(sql);
if (rows.length) {
const delete_sql = `delete FROM users where id=${req.params.userId};`;
await db.query(delete_sql);
return res.status(200).json({ mesaage: "deleted" });
} else {
const err = new Error("USER_NOT_FOUND")
err.status = 404
throw err
}
} catch (e) {
return res.status(e.status || 500).json({message: e.message || "SERVER_ERROR"})
}
});
userId가 일치하는 객체가 없는 경우 else 블럭 안으로 들어오게 되고, "USER_NOT_FOUND"라는 메세지를 에러 객체를 생성해 err변수에 저장합니다. err.status를 사용해 상태코드도 404로 저장합니다.
throw를 사용해 해당 err 객체를 전달하면 try...catch구문의 catch(e){}블럭에서 오류를 e로 받아 핸들링할 수 있습니다.
아래처럼 변수를 선언하지 않고 바로 throw도 가능합니다.
} else {
throw {status:404, message:"USER_NOT_FOUND"}
}
} catch (e) {
return res.status(e.status || 500).json({message: e.message || "SERVER_ERROR"})
}
});
728x90
'프로젝트 > wecode : 기업협업' 카테고리의 다른 글
((기업협업5)) 팔로우, 팔로워 raw query로 데이터 가져오기 (1) | 2022.09.04 |
---|---|
((기업협업4)) router에 때려적었던 지저분한 스파게티 코드 분리하기 (0) | 2022.08.20 |
((기업협업4)) AWS : DUMP MYSQL RDS TO LOCAL MYSQL (0) | 2022.08.19 |
((기업협업3)) node.js + mysql + CRUD 특정 유저 삭제 (0) | 2022.08.18 |
((기업협업3)) node.js + mysql + CRUD 특정 유저 수정 (0) | 2022.08.18 |