NodeJS exception 예외 처리
처리하지 못한 에러
- 서버 스레드를 멈추게 함
- 노드는 기본적으로 싱글 스레드라 스레드가 멈춘다는 건 프로세스가 멈춘다는 거
- 에러 처리는 필수
- try catch
- 기본적으로 에러가 발생할 만한 코드를 try catch로 감쌈
setInterval(() => {
try {
throw new Error("에러 발생");
} catch (err) {
console.error(err);
}
}, 1000);
- node 비동기 메서드의 err는 따로 처리하지 않아도 됨
const fs = require("fs").promises;
setInterval(() => {
fs.readFile("./text.txt")
.then((data) => {
throw new Error("에러 발생");
})
.catch((err) => {
console.error(err);
})
}, 1000);
- process.on("uncaughtException", (err)) : 모든 에러 기록(처리 아님)
- throw new Error를 process.on(uncaughtException)이 받음
setInterval(() => {
fs.readFile("./text.txt")
.then((data) => {
throw new Error("에러 발생");
})
}, 1000);
process.on("uncaughtException", (err) => {
console.error(err);
})
'서버 > Node' 카테고리의 다른 글
NodeJS NPM semver package.json (0) | 2022.01.19 |
---|---|
NodeJS fs (0) | 2022.01.18 |
NodeJS process (0) | 2022.01.18 |
NodeJS event (0) | 2022.01.18 |
NodeJS path (0) | 2022.01.18 |