MyException을 포착하지 않는 다음 함수가 있습니다.
const myFunction = () => async (req, res, next) => {
try {
myHTTPRequest().then(async (response) => {
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
})
.catch((error) => {
throw error; //Doesn't work
});
} catch (error) {
console.log('This block should catch MyException, but it doesn't');
next(error);
}
};
대신 응용 프로그램은 다음 오류 메시지를 콘솔에 씁니다.
(node:45746) UnhandledPromiseRejectionWarning
(node:45746) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:45746) [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.
문제는 예상되는 Catch-Block에서 MyException을 잡기 위해 코드를 어떻게 조정해야합니까?
문제는 당신이 혼합하고 있다는 것입니다 .then/.catch
함께 try/catch
.
함수 try/catch
에 코드를 입력하려면 에 키워드 async
를 사용해야 await
합니다 Promise
.
.catch
아무것도하지 않고 오류를 다시 던지고 있으므로 삭제할 수 있습니다 .UnhandledPromiseRejectionWarning
const myFunction = () => (req, res, next) => {
try {
const response = await myHTTPRequest();
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
} catch (error) {
next(error);
}
};
코드 .then/catch
없이 사용하면 async/await
다음과 같습니다.
const myFunction = () => (req, res, next) => {
myHTTPRequest().then((response) => {
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
})
.catch((error) => {
throw error;
// It makes no sense to throw again in here
// But I'm showing you how to handle it if you do
})
.catch(error => {
next(error);
})
};
물론 이중 .catch
은 의미가 없으므로 제거하고 단일 항목을 남겨야합니다.
const myFunction = () => (req, res, next) => {
myHTTPRequest().then((response) => {
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
})
.catch(error => {
next(error);
})
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다