pascalav
pascalav
DDeno
Created by pascalav on 9/13/2023 in #help
How to handle a user abort by Deno.serve
Hello, I have a question and discovered this Discord channel now. The Deno website has an example at: https://deno.land/manual@v1.36.4/runtime/http_server_apis#inspecting-the-incoming-request There is the note below: Be aware that the req.text() call can fail if the user hangs up the connection before the body is fully received. Make sure to handle this case. However, I have not found a sample how to catch this case. Can Deno detect that the connection has been terminated? I take the example from the Deno site and changed it a bit:
const abortController = new AbortController();
Deno.addSignalListener('SIGINT', () => {
abortController.abort();
});

Deno.serve(
{
port:3000,
signal: abortController.signal
},
async (req) => {
if (req.body) {
try {
console.log('Start');
const body = await req.formData();
for (const key of body.keys()) {
console.log(key);
}
console.log('Never reached, when user abort.');
} catch {
// Will not be triggered on abort.
console.log('Error on await req.formData()');
}
}

return new Response("Hello, World!");
}
);
const abortController = new AbortController();
Deno.addSignalListener('SIGINT', () => {
abortController.abort();
});

Deno.serve(
{
port:3000,
signal: abortController.signal
},
async (req) => {
if (req.body) {
try {
console.log('Start');
const body = await req.formData();
for (const key of body.keys()) {
console.log(key);
}
console.log('Never reached, when user abort.');
} catch {
// Will not be triggered on abort.
console.log('Error on await req.formData()');
}
}

return new Response("Hello, World!");
}
);
By the way, I added the "AbortHandler" for the test. If await req.formData() passes successfully, the server can be terminated with Ctrl + C in the terminal (Linux Mint). If the user cancels the "upload", after the Ctrl + C command is still running a process until I close the terminal. I think that is why Deno writes on the website, you have to catch this case. How to do this?
9 replies