You can simply remove async keyword from the lambda function and add catch clause to prevent an unhandled promise rejection.
process.on("uncaughtException", (error: Error) => {
this.errorHandler(error).catch((e) => console.error(e));
});
The reason you are getting this error is, process.on
expects its lambda function to return void
, not Promise<void>
, and your lambda function is never going to be awaited.
This is important, because without await keyword an unhandled promise rejection may be triggered which crashes the entire process immediately.
Look at the following example:
function middleware(f) {
f();
}
middleware(async () => {
throw "Error!";
});
Now, when I run this file, an error message will pop up:
node:internal/process/promises:289
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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(). The promise rejected with the reason "Error!".] {
code: 'ERR_UNHANDLED_REJECTION'
}
This is because the promise was never awaited, and therefore Node.js didn't know what to do with the error thrown by the promise.
Simply adding catch like this clause will fix the problem.
function middleware(f) {
f().catch((e) => console.error(e));
}
middleware(async () => {
throw "Error!";
});
Note: adding catch clause is not mandatory in a browser environment because unhandled promise rejection will not result in immediate crash in the browser environment.
async
function always returns a promise, so it can't be passed where a void function is expected. Why not just call the error handler, what are you trying to wait for? – Abradeasync
functions into things that won't use the promise they return. TypeScript is helping you avoid doing that with this error. – Heigl