Micke
Micke10mo ago

Send custom response inside error event listener

If I add an event listener for errors in Deno to catch anything my middleware error handler doesn't, how would I send back a custom response (status + body) to the client, rather than the default 500 internal server error? app.addEventListener("error", (event: any) => { log.error("Uncaught error:" + event.error) });
2 Replies
Deno AI Helper
Deno AI Helper10mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the code snippet you've provided, it seems like you're trying to add an error event listener to an app object, which I assume is an instance of an HTTP server or framework. In many server frameworks, you would typically handle errors by defining a middleware that catches errors and sends a custom response. However, without knowing the specific framework you're using within Deno (since Deno itself doesn't provide an app object with an addEventListener method for HTTP servers), I can't give you a precise answer. If your framework supports an error event listener and allows you to modify the response, you would need to access the response object from the event parameter and set the status and body accordingly. However, this is speculative advice and not based on the Deno documentation, so please double-check the accuracy of this advice with the documentation or community for the specific framework you are using. Here's a generic example of what this might look like, but remember this is not from the Deno documentation and may not work with your specific setup:
app.addEventListener("error", (event: any) => {
log.error("Uncaught error:" + event.error);
// Assuming `event` has a `response` object you can modify:
if (event.response) {
event.response.status = 500; // Set the status code
event.response.body = "Custom error message"; // Set the response body
}
});
app.addEventListener("error", (event: any) => {
log.error("Uncaught error:" + event.error);
// Assuming `event` has a `response` object you can modify:
if (event.response) {
event.response.status = 500; // Set the status code
event.response.body = "Custom error message"; // Set the response body
}
});
Please make sure to consult the documentation or community for the framework you're using to get the correct way to handle such scenarios.
Micke
Micke10mo ago
Tried setting those attributes, but they didn't have any effect on the response