Skip to content

Commit

Permalink
fix: application errors dispatched after default logic
Browse files Browse the repository at this point in the history
Fixes #630
  • Loading branch information
kitsonk committed Jan 26, 2024
1 parent a854c72 commit f37796b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
21 changes: 21 additions & 0 deletions application.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,27 @@ Deno.test({
},
});

Deno.test({
name: "errors call event handler properly",
async fn() {
const [serverConstructor, responseStack] = setup([]);
const app = new Application({ serverConstructor, logErrors: false });
app.use((ctx) => {
ctx.throw(400, "Bad Request");
});
const errStatusStack: (Status | undefined)[] = [];
app.addEventListener("error", (evt) => {
errStatusStack.push(evt.context?.response.status);
});
await app.listen({ port: 8000 });
const [response] = responseStack;
assertEquals(response.status, 400);
assertEquals(errStatusStack.length, 1);
assertEquals(errStatusStack[0], Status.BadRequest);
teardown();
},
});

Deno.test({
name: "caught errors don't dispatch error events",
async fn() {
Expand Down
5 changes: 4 additions & 1 deletion application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,10 @@ export class Application<AS extends State = Record<string, any>>
error = new Error(`non-error thrown: ${JSON.stringify(error)}`);
}
const { message } = error;
this.dispatchEvent(new ApplicationErrorEvent({ context, message, error }));
if (!context.response.writable) {
this.dispatchEvent(
new ApplicationErrorEvent({ context, message, error }),
);
return;
}
for (const key of [...context.response.headers.keys()]) {
Expand All @@ -438,6 +440,7 @@ export class Application<AS extends State = Record<string, any>>
? error.status
: 500;
context.response.body = error.expose ? error.message : STATUS_TEXT[status];
this.dispatchEvent(new ApplicationErrorEvent({ context, message, error }));
}

/** Processing registered middleware on each request. */
Expand Down

0 comments on commit f37796b

Please sign in to comment.