Why isn't this error caught?

Basic code example:
try {
Deno.remove("fakefile");
} catch (err) {
console.log("File doesn't exist...");
}

console.log("That file didn't exist");
try {
Deno.remove("fakefile");
} catch (err) {
console.log("File doesn't exist...");
}

console.log("That file didn't exist");
The output when you run this is the following:
❯ deno run -A delete.js
That file didn't exist
error: Uncaught (in promise) NotFound: No such file or directory (os error 2), remove 'fakefile'
at async Object.remove (ext:deno_fs/30_fs.js:175:3)
❯ deno run -A delete.js
That file didn't exist
error: Uncaught (in promise) NotFound: No such file or directory (os error 2), remove 'fakefile'
at async Object.remove (ext:deno_fs/30_fs.js:175:3)
So the code within the catch statement isn't running, but the code after the catch statement is executed. And yet the program crashes due to an uncaught error.
4 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
General Beef 🥩
Interesting, I'll give this a try. Thanks!
Doctor 🤖
Doctor 🤖2y ago
You don’t need to handle it like this. You just need to await it within the try catch. Not awaiting it will let the try catch continue down and out, not catching any errors that the promise may throw.
// this will only throw an error if the fetch function fails to return a promise.
try {
return fetch()
} catch {}

// this will catch any errors the promise will throw as well as if it fails to return a promise.
try {
return await fetch()
} catch {}
// this will only throw an error if the fetch function fails to return a promise.
try {
return fetch()
} catch {}

// this will catch any errors the promise will throw as well as if it fails to return a promise.
try {
return await fetch()
} catch {}
Basically where the promise is being resolved is where the errors from the promise will be thrown and caught.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View