Repository navigation
fix(core): avoid treating error instances with statusCode as http errors - #17709
Conversation
micalevisk
left a comment
There was a problem hiding this comment.
Thanks for picking this up. The core idea is right: on master the trailing !!(err.statusCode && err.message) is equivalent to the check that #14753 replaced, which makes the FastifyError and "http-errors" guards above it moot and reopens #14738. Excluding real Error instances from that fallback does fix the Elasticsearch ResponseError case from #17695.
Requesting changes for three things (details in the inline comments):
-
This changes behavior for framework-native errors, but the PR is marked non-breaking. Nest installs this filter as the Fastify/Express error handler, so an
Errorcarrying astatusCodethat is thrown from a Fastify hook, or passed tonext()in Express middleware, used to reach the client with its status and message. It now becomes a 500. I reproduced both againstmasterand this branch. -
Half of the new condition has no test. Mutating the condition and re-running
exceptions-handler.spec.ts:Mutation Spec result remove !(err instanceof Error)fails (caught) change >= 400to> 400fails (caught) remove Number.isInteger(err.statusCode)passes (not caught) remove err.statusCode < 600passes (not caught) remove Boolean(err.message)passes (not caught) The tests suggested inline catch all three. They also cover the non-object guard at the top of
isHttpError, which currently has no test. -
The duplicated and vacuous tests that #17695 points out are still in the spec.
Non-blocking and pre-existing: the FastifyError branch accepts any numeric statusCode, while the fallback now requires 4xx/5xx. A FastifyError created with a non-error status would still have its status and message sent to the client. Worth aligning while touching this method, or leaving a comment explaining why not.
I also looked for other code paths with the same bug and found none. BaseWsExceptionFilter and BaseRpcExceptionFilter never send a foreign error's message to the client, and the adapters' mapException only convert FastifyError, SyntaxError and URIError.
| // Plain "http error"-shaped values (e.g. non-Error objects thrown by third-party | ||
| // middleware) that carry a valid HTTP status code and a message | ||
| return ( | ||
| !(err instanceof Error) && |
There was a problem hiding this comment.
Excluding Error instances is the right fix for SDK errors, but it also affects errors that users raise on purpose through the underlying framework. RoutesResolver#registerExceptionHandler installs this filter as the Fastify/Express error handler, so those errors reach isHttpError too. A scratch e2e test run against both branches:
| Scenario | master |
this PR |
|---|---|---|
Fastify onRequest hook throws Object.assign(new Error('forbidden by hook'), { statusCode: 403 }) |
403 {"statusCode":403,"message":"forbidden by hook"} |
500 {"statusCode":500,"message":"Internal server error"} |
Express middleware calls next() with that same error |
403 {"statusCode":403,"message":"forbidden by hook"} |
500 {"statusCode":500,"message":"Internal server error"} |
Fastify itself uses a thrown error's statusCode as the response status, and that is exactly the shape of Elasticsearch's ResponseError, so a shape check can't keep one and drop the other. I think 500 is the safer default. Fastify's own error-handling docs warn that "a status code below 500 is not on its own a guarantee that the message is safe to expose". But then:
- please mark this as a breaking change in the PR description, with the migration path: throw an
HttpException, or map those errors in a custom exception filter; - please add an e2e test for it, e.g. next to the existing cases in
integration/hello-world/e2e/exceptions.spec.ts, so any future loosening of this fallback fails a test. The unit tests didn't catch the last one.
| typeof err.statusCode === 'number' && | ||
| Number.isInteger(err.statusCode) && |
There was a problem hiding this comment.
Number.isInteger never coerces and returns false for anything that isn't a number, so the typeof check adds nothing. The spec still passes with it removed.
| typeof err.statusCode === 'number' && | |
| Number.isInteger(err.statusCode) && | |
| Number.isInteger(err.statusCode) && |
| Number.isInteger(err.statusCode) && | ||
| err.statusCode >= 400 && | ||
| err.statusCode < 600 && | ||
| Boolean(err.message) |
There was a problem hiding this comment.
Nit, not introduced by this PR: the return type promises message: string, but any truthy value passes here. Something like { statusCode: 400, message: { query: '…' } } gets serialized into the response body as-is. If the guard should match the declared type, typeof err.message === 'string' && err.message !== '' would do it.
Separately, removing this clause entirely doesn't fail any test today. The tests suggested on the spec cover it.
| }); | ||
| }); | ||
| it('should not treat errors from external API calls as errors from "http-errors" library', () => { | ||
| it('should not treat errors from external API calls with statusCode as http errors', () => { |
There was a problem hiding this comment.
Since this test is being touched: the two problems #17695 points out in this file are still here after this PR.
should treat fastify errors as http errorsexists twice, verbatim (lines 57 and 85). The second copy can go.- The original
should not treat errors from external API calls as errors from "http-errors" librarytest (line 72) still builds the error with{ status: 400 }. The fallback only readsstatusCode, so that test never exercised it, and this renamed test now covers the real case. It can be removed.
| statusCode: 500, | ||
| message: 'Internal server error', | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Suggested cases for the clauses nothing tests yet. With these added right after this test, all 27 tests pass on this branch. Each of the following mutations then fails exactly one test: removing Number.isInteger(...), removing < 600, changing it to < 599, removing Boolean(err.message), and removing the !err || typeof err !== 'object' guard (which the null case now covers).
it('should treat plain http-error shaped objects with the highest 5xx status code as http errors', () => {
const plainHttpError = {
statusCode: 599,
message: 'Upstream failure',
};
handler.next(plainHttpError, new ExecutionContextHost([0, response]));
expect(statusStub).toHaveBeenCalledWith(599);
expect(jsonStub).toHaveBeenCalledWith({
statusCode: 599,
message: 'Upstream failure',
});
});
[
{ statusCode: 600, message: 'Status code above 5xx' },
{ statusCode: 400.5, message: 'Non-integer status code' },
{ statusCode: 400, message: '' },
null,
'Some thrown string',
].forEach(value => {
it(`should not treat ${JSON.stringify(value)} as an http error`, () => {
handler.next(value, new ExecutionContextHost([0, response]));
expect(statusStub).toHaveBeenCalledWith(500);
expect(jsonStub).toHaveBeenCalledWith({
statusCode: 500,
message: 'Internal server error',
});
});
});7d62987 to
a347ace
Compare
statusCode as http errors
|
Thank you for the thorough review and suggestions @micalevisk! All items have been addressed:
|
Fastify's schema validation errors are plain errors with a statusCode, so since #17709 they are answered with a 500. Treat errors with the FST_ERR_VALIDATION code like FastifyError again.
| datasource | package | from | to | | ---------- | ------------------------ | ------ | ------ | | npm | @nestjs/common | 12.0.1 | 12.1.0 | | npm | @nestjs/core | 12.0.1 | 12.1.0 | | npm | @nestjs/platform-express | 12.0.1 | 12.1.0 | ## [v12.1.0](https://github.com/nestjs/nest/releases/tag/v12.1.0) ##### v12.1.0 (2026-09-23) ##### Bug fixes - `core` - [#17838](nestjs/nest#17838) fix(core): inherit optional ctor params when the ctor is not redeclared ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17819](nestjs/nest#17819) fix(core): name the module when metadata entries are invalid ([@thekhegay](https://github.com/thekhegay)) - `microservices` - [#17828](nestjs/nest#17828) fix(microservices): let the redis client retry after a failed connect ([@hktitof](https://github.com/hktitof)) - [#17810](nestjs/nest#17810) fix(microservices): fail every pending request when a callback throws ([@hktitof](https://github.com/hktitof)) ##### Enhancements - `core` - [#17846](nestjs/nest#17846) fix(core): do not skip subsequent middleware after a transient one ([@lehafari](https://github.com/lehafari)) - [#17840](nestjs/nest#17840) fix(core): preserve route handler names ([@Grmiade](https://github.com/Grmiade)) - `common`, `core` - [#17713](nestjs/nest#17713) feat(core): add support for array of global prefixes ([@micalevisk](https://github.com/micalevisk)) - [#17834](nestjs/nest#17834) feat(common,core): add built-in, adapter-agnostic cookies ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - `platform-fastify` - [#17824](nestjs/nest#17824) fix(fastify): honor Nest forceCloseConnections in initHttpServer ([@xia-chao](https://github.com/xia-chao)) - `common` - [#17827](nestjs/nest#17827) fix(common): apply the ParseDatePipe default to every missing value ([@xia-chao](https://github.com/xia-chao)) - `platform-fastify`, `testing` - [#17835](nestjs/nest#17835) feat(fastify): add file upload interceptors backed by [@fastify/multipart](https://github.com/fastify/multipart) ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - `common`, `core`, `platform-fastify` - [#17836](nestjs/nest#17836) feat(common,core,fastify): built-in CSRF protection and security headers ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) ##### Committers: 9 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Alejandro ([@lehafari](https://github.com/lehafari)) - Chris Z ([@haimingZZ](https://github.com/haimingZZ)) - Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - Jérémy Fauvel ([@Grmiade](https://github.com/Grmiade)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk)) - Roman Khegay ([@thekhegay](https://github.com/thekhegay)) - Xia Chao ([@xia-chao](https://github.com/xia-chao)) ## [v12.0.4](https://github.com/nestjs/nest/releases/tag/v12.0.4) ##### v12.0.4 (2026-09-21) ##### Bug fixes - `microservices` - [#17816](nestjs/nest#17816) fix(microservices): let the kafka client retry after a failed connect ([@Xch4rt](https://github.com/Xch4rt)) - [#17786](nestjs/nest#17786) fix(microservices): fail pending rmq requests on client close ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - [#17802](nestjs/nest#17802) fix(microservices): fail pending nats requests on client close ([@hktitof](https://github.com/hktitof)) - [#17803](nestjs/nest#17803) fix(microservices): handle missing grpc package namespace gracefully ([@Se3do](https://github.com/Se3do)) - [#17799](nestjs/nest#17799) fix(microservices): share the processing hook envelope across transports ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17797](nestjs/nest#17797) fix(microservices): close the kafka request-response span exactly once ([@MingLin1995](https://github.com/MingLin1995)) - [#17794](nestjs/nest#17794) fix(microservices): close the request-response span exactly once ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17785](nestjs/nest#17785) fix(microservices): route message handler rejections to handleError ([@hktitof](https://github.com/hktitof)) - `core` - [#17821](nestjs/nest#17821) fix(core): hang on sparse factory inject array ([@xia-chao](https://github.com/xia-chao)) ##### Enhancements - `platform-express` - [#17818](nestjs/nest#17818) Fix: merge multer `limits` key-by-key instead of overriding it wholesale ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy)) - `common` - [#17780](nestjs/nest#17780) fix(common): mark parse date pipe options as optional ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid)) ##### Dependencies - `common` - [#17793](nestjs/nest#17793) fix(deps): update dependency file-type to v22.1.1 ([@renovate\[bot\]](https://github.com/apps/renovate)) - `platform-fastify` - [#17791](nestjs/nest#17791) fix(deps): update dependency fastify to v5.12.5 ([@renovate\[bot\]](https://github.com/apps/renovate)) ##### Committers: 10 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Chowdhury Zaber Bin Zahid ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid)) - Imad - Prakticode ([@prakticode](https://github.com/prakticode)) - Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - MD. Ridoy Babu ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy)) - Ming ([@MingLin1995](https://github.com/MingLin1995)) - Mohammed Said ([@Se3do](https://github.com/Se3do)) - Pablo Gutiérrez ([@Xch4rt](https://github.com/Xch4rt)) - Xia Chao ([@xia-chao](https://github.com/xia-chao)) ## [v12.0.3](https://github.com/nestjs/nest/releases/tag/v12.0.3) ##### v12.0.3 (2026-09-15) ##### Bug fixes - `microservices` - [#17766](nestjs/nest#17766) fix(microservices): always run the kafka processing end hook ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17757](nestjs/nest#17757) fix(microservices): fail pending requests on client close ([@hktitof](https://github.com/hktitof)) - [#17746](nestjs/nest#17746) fix(microservices): bound memory held for a TCP peer ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17745](nestjs/nest#17745) fix(microservices): destroy open TCP sockets on shutdown ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - `common` - [#17738](nestjs/nest#17738) fix(common): validate uuid version and variant when no version is set ([@otnc](https://github.com/otnc)) - [#17761](nestjs/nest#17761) fix(common): invoke proto-key stripping hook via this in transform ([@koreahghg](https://github.com/koreahghg)) ##### Dependencies - `platform-express` - [#17762](nestjs/nest#17762) fix(deps): update dependency multer to v2.4.0 ([@renovate\[bot\]](https://github.com/apps/renovate)) - `common` - [#17753](nestjs/nest#17753) fix(deps): update dependency file-type to v22.1.0 ([@renovate\[bot\]](https://github.com/apps/renovate)) ##### Committers: 4 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - otoneko. ([@otnc](https://github.com/otnc)) - 한국 ([@koreahghg](https://github.com/koreahghg)) ## [v12.0.2](https://github.com/nestjs/nest/releases/tag/v12.0.2) ##### v12.0.2 (2026-09-14) ##### Bug fixes - `platform-socket.io`, `platform-ws` - [#17666](nestjs/nest#17666) fix(socket.io): keep the message stream alive when a handler throws ([@hktitof](https://github.com/hktitof)) - `microservices` - [#17728](nestjs/nest#17728) fix(microservices): detach signal listeners of connected microservices ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17671](nestjs/nest#17671) fix(microservices): fail requests whose reply subscription is rejected ([@samuelmbabhazi](https://github.com/samuelmbabhazi)) - [#17670](nestjs/nest#17670) fix(microservices): do not treat foreign JSON as an RPC envelope ([@xia-chao](https://github.com/xia-chao)) - [#17644](nestjs/nest#17644) fix(microservices): don't flatten plain handler results with pre-request hooks ([@iamolegga](https://github.com/iamolegga)) - [#17641](nestjs/nest#17641) fix(microservices): run the mqtt listen callback once ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - `common` - [#17710](nestjs/nest#17710) fix(common): collapse duplicate internal slashes in `normalizePath` ([@Asadshah7950](https://github.com/Asadshah7950)) - [#17655](nestjs/nest#17655) fix(common): validate UUID v3 variant ([@gwagjiug](https://github.com/gwagjiug)) - [#17702](nestjs/nest#17702) fix(common): treat empty string as array input in ParseArrayPipe ([@xia-chao](https://github.com/xia-chao)) - `core` - [#17667](nestjs/nest#17667) fix(core): discover factory providers with discovery decorators ([@hktitof](https://github.com/hktitof)) - [#17709](nestjs/nest#17709) fix(core): avoid treating error instances with `statusCode` as http errors ([@Asadshah7950](https://github.com/Asadshah7950)) - [#17625](nestjs/nest#17625) fix(core): clean up repeated shutdown signal listeners ([@Raj4478](https://github.com/Raj4478)) - `platform-fastify` - [#17705](nestjs/nest#17705) fix(fastify): derive neutral version when accept header is absent ([@Gaurav1112](https://github.com/Gaurav1112)) - [#17699](nestjs/nest#17699) fix(fastify): send responses for exceptions thrown from middleware ([@micalevisk](https://github.com/micalevisk)) ##### Enhancements - `microservices` - [#17734](nestjs/nest#17734) feat(microservices): add maxConnectionAttempts to ServerMqtt ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) ##### Dependencies - `platform-fastify` - [#17729](nestjs/nest#17729) fix(deps): update dependency fastify to v5.12.4 ([@renovate\[bot\]](https://github.com/apps/renovate)) ##### Committers: 16 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Alexey Solovyov ([@lyohaplotinka](https://github.com/lyohaplotinka)) - Asad Ali Shah ([@Asadshah7950](https://github.com/Asadshah7950)) - Gyeonghun Park ([@Gyeonghun-Park](https://github.com/Gyeonghun-Park)) - Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - Kumar Gaurav ([@Gaurav1112](https://github.com/Gaurav1112)) - Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk)) - Ming ([@MingLin1995](https://github.com/MingLin1995)) - Mohammed Said ([@Se3do](https://github.com/Se3do)) - Rajeshwar Singh ([@Raj4478](https://github.com/Raj4478)) - Xia Chao ([@xia-chao](https://github.com/xia-chao)) - [@iamolegga](https://github.com/iamolegga) - cui fliter ([@cuishuang](https://github.com/cuishuang)) - samuel mbabhazi ([@samuelmbabhazi](https://github.com/samuelmbabhazi)) - 곽지욱 ([@gwagjiug](https://github.com/gwagjiug))
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Currently, in
BaseExceptionFilter.isHttpError(err):If an application invokes an external SDK, database client, or service (such as Elasticsearch client
ResponseError, AWS SDK error, or other third-party libraries) that throws an instance ofErrorcarrying astatusCodeproperty (e.g.400or404),isHttpErrorreturnstrue.This causes the exception filter to treat external client/backend errors as client-facing HTTP responses, inadvertently exposing internal error details and messages to the API consumer instead of catching them as unexpected unhandled exceptions (500 Internal Server Error).
Issue Number: #17695
What is the new behavior?
BaseExceptionFilter.isHttpErrornow verifies that the error value:instanceof Error(preserving dedicated checks forFastifyErrorandhttp-errorsearlier in the method).statusCodewithin valid HTTP error status ranges (between 400 and 599).message(typeof err.message === 'string' && err.message !== '').This allows plain HTTP error-shaped objects thrown by middleware/plugins to continue being recognized while preventing arbitrary external SDK
Errorinstances from accidentally exposing internal details.Unit and e2e tests have been added:
exceptions-handler.spec.ts: Cleaned up duplicate fastify test and outdated status test; added tests for 599 boundary and invalid/non-integer/empty message status checks.integration/hello-world/e2e/exceptions.spec.ts: Added e2e assertions for both Express and Fastify verifying thatErrorinstances carryingstatusCoderesult in a 500 Internal Server Error.Does this PR introduce a breaking change?
Breaking change & Migration:
Framework errors or custom errors instantiated as
new Error()with an assignedstatusCode(e.g. via Fastify hooks or Express middleware) will no longer be treated as client HTTP responses and will instead yield a500 Internal Server Error.HttpException(e.g.,throw new ForbiddenException(...)), or catch and map those error classes using a custom NestJSExceptionFilter.Other information
All unit tests and e2e integration tests pass cleanly.