unhandled promise rejection
(node:17928) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error
(node:17928) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
우선 unhandled promise rejection을 보겠습니다.
어떤 상황에서 나타나는가: UnhandledPromise Rejection Warning
또는 unhandled promise rejection이 무엇입니까
Promise의 상태가rejection으로 바뀌었을 때, 프로세스가 포착될 때까지 제대로 처리하지 않았습니다.이 Promise는 unhandled promise rejection이라고 불린다.
Promise 예외는 다음과 같은 두 가지 트리거가 있습니다.
// reject
new Promise((resolve, reject) => {
reject('timeout');
});
// exception
new Promise((resolve, reject) => {
undefinedVariable();
});
우리는 두 가지 방식으로 리제이션을 처리하는데, 두 번째는 방식 1의 문법 설탕이다.
// .then(undefined, () => {})
new Promise((resolve, reject) => {
// ...
reject('timeout');
}).then(undefined, (error) => {
console.error(error);
});
// .catch(() => {})
new Promise((resolve, reject) => {
// ...
reject('timeout')
}).catch((error) => {
console.error(error);
})
관건은 이상을 계속 위로 던질 수 없다는 것이다. 그렇지 않으면 unhandled promise rejection을 촉발할 것이다.다음 코드와 같습니다.
//
new Promise((resolve, reject) => {
// ...
reject('timeout');
}).then(undefined, (error) => {
throw new Error(error);
});
//
new Promise((resolve, reject) => {
// ...
reject('timeout');
}).catch((error) => {
throw new Error(error);
});
원인은 상관없다.onFulfilled, onRejection) 중의 onFulfilled인지 onRejection이 되돌아오는 것은 모두 Promise입니다. 만약 그들 내부에서 이상을 던졌다면 다음 thenchains는 여전히 Rejection이라는 것을 의미합니다.
const promise2 = (new Promise((resolve, reject) => {
// ...
reject('timeout');
}).catch((error) => {
throw new Error(error);
}));
여기서promise2에 대해 말하자면, 그것의rejectiton은 아직handle에 의해 처리되지 않았다.따라서 다음과 같이 처리해야 한다.
const promise2 = (new Promise((resolve, reject) => {
// ...
reject('timeout');
}).catch((error) => {
throw new Error(error);
}));
promise2.catch((error) => {
console.error(error);
});
Async/Await
Async/Await에서 unhandled promise rejection은 다음과 같이 촉발됩니다.
// Promise
;(async () => {
await (new Promise((resolve, reject) => {
reject('timeout');
}));
})();
// async
;(async () => {
try {
await (new Promise((resolve, reject) => {
reject('timeout');
}));
} catch(e) {
throw new Error(e);
}
})();
어떻게 오류 창고를 얻을 수 있습니까
Node.js v8.1.2 Documentation: https://nodejs.org/api/process.html#process_event_unhandledrejection
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.