Closed artze closed 9 months ago
Had a look at the #handleError()
in Application
class.
It may be because the ApplicationErrorEvent
is dispatched (see here) before the context.response.status
is set on L433.
From what I can understand, if unset, the response.status
defaults to 404
(if the response.body
is empty). It looks like the uncaught error gets logged before the response.status
is set, and takes the default value.
The ApplicationErrorEvent
getting called before setting the context response status being set is intentional, because this allows the event handler to change the context/response based on error information.
It is worth looking into setting the status before calling the handler and still allow the handler to override the value.
For me, the status code sent back to the client is still a 404 when using oak 13.0.0, am I missing something?
@SaTae66
When using ctx.throw(400)
like in my setup above (note that I do not have any error handling middleware defined), the correct status code is sent to the client (400
), but the [uncaught application error]
logs says something different (404
).
@artze if I do sth like
router.use(ErrorMiddleware.unauthorized);
with
static async unauthorized(ctx: oak.RouterContext<string>, next: oak.Next) {
const { response } = ctx;
try {
await next();
} catch (err) {
if (err instanceof oak.httpErrors.Unauthorized) {
// required by https://www.rfc-editor.org/rfc/rfc9110#status.401
response.headers.set("WWW-Authenticate", "Bearer");
}
}
}
and throwing the error like
ctx.throw(401);
the WWW-Authenticate
header is set (so the error caught is a 401
), but the status received by the client is a 404
.
If I remove the ErrorMiddleware, I (obviously) receive an [uncaught application error]: UnauthorizedError - Unauthorized
, but the client receives the correct 401
status code.
Caught errors do not automatically affect the response. It is only uncaught errors that are handled automatically and dispatch error events. If you still want automatic error processing to occur, don't catch the errors.
The observed behaviour aligns to the behaviour in these tests:
Ah ok, thanks a lot for the clarification!
Hi,
There might be an issue with
[uncaught application error]
logger. No matter what uncaught errors are thrown in the app, the log always showsresponse.status=404
.Setup
Output
App logs:
+++
Made the request with
curl
. The requester received the expected status code:Expected Behavior
response.status
in[uncaught application error]
log should reflect the status code thrown in the app.Environment
Thank you