Exception handler with Fastify leaks internals if content type is set

See original GitHub issue

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

import { Controller, Get, Header } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Header('Content-Type', 'text/xml')
  get(): string {
    throw new Error();
    // return 'ok';
  }
}

Throw an error:

[1635460397235] ERROR (6802 on MacBook-Pro.fritz.box): Promise errored, but reply.sent = true was set
    reqId: "req-1"
    err: {
      "type": "FastifyError",
      "message": "Attempted to send payload of invalid type 'object'. Expected a string or Buffer.",
      "stack":
          FastifyError: Attempted to send payload of invalid type 'object'. Expected a string or Buffer.
              at onSendEnd (/Users/thomaschaaf/develop/x/x-api/node_modules/fastify/lib/reply.js:430:11)
              at onSendHook (/Users/thomaschaaf/develop/x/x-api/node_modules/fastify/lib/reply.js:390:5)
              at _Reply.Reply.send (/Users/thomaschaaf/develop/x/x-api/node_modules/fastify/lib/reply.js:193:3)
              at FastifyAdapter.reply (/Users/thomaschaaf/develop/x/x-api/node_modules/@nestjs/platform-fastify/adapters/fastify-adapter.js:46:29)
              at ExceptionsHandler.handleUnknownError (/Users/thomaschaaf/develop/x/x-api/node_modules/@nestjs/core/exceptions/base-exception-filter.js:38:24)
              at ExceptionsHandler.catch (/Users/thomaschaaf/develop/x/x-api/node_modules/@nestjs/core/exceptions/base-exception-filter.js:17:25)
              at ExceptionsHandler.next (/Users/thomaschaaf/develop/x/x-api/node_modules/@nestjs/core/exceptions/exceptions-handler.js:16:20)
              at Object.<anonymous> (/Users/thomaschaaf/develop/x/x-api/node_modules/@nestjs/core/router/router-proxy.js:13:35)
              at processTicksAndRejections (internal/process/task_queues.js:93:5)
      "name": "FastifyError",
      "code": "FST_ERR_REP_INVALID_PAYLOAD_TYPE",
      "statusCode": 500
    }

and results in a response like this:

{
  "statusCode": 500,
  "code": "FST_ERR_REP_INVALID_PAYLOAD_TYPE",
  "error": "Internal Server Error",
  "message": "Attempted to send payload of invalid type 'object'. Expected a string or Buffer."
}

Minimum reproduction code

See above

Steps to reproduce

No response

Expected behavior

Should not pass fastify error to the enduser

Package

Other package

No response

NestJS version

8.1.2

Packages versions

Node.js version

No response

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:4
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
kamilmysliwieccommented, Dec 23, 2021

Well, so this one is problematic. The default, built-in exception filter automatically converts all errors to a JSON-compatible format (to respond with the “Internal server error” in case it received an unexpected error it cannot recognize/classify).

Now, if you change the content type to, let’s say, application/pdf (or XML), Fastify throws an exception because the exception filter automatically tries to respond with the JSON object. However, we can’t really add checks for all possible content types (because that wasn’t the goal from the early beginning) you could potentially use in your app to the exception filter. I’m not even sure if we should classify this as a “bug”, instead, I think we should just add a warning (within the filter) that the default response format is JSON and if you want to auto-react to errors thrown from within handlers that support xml/etc you should attach a custom filter (to format the error accordingly).

0reactions
kamilmysliwieccommented, Oct 31, 2022
Read more comments on GitHub >

github_iconTop Results From Across the Web

Errors - Fastify
When a custom error handler has been defined through setErrorHandler , the custom ... Body cannot be empty when content-type is set to...
Read more >
Reply - Fastify
If you not set a 'Content-Type' header, Fastify assumes that you are using 'application/json' , unless you are send a stream, in that...
Read more >
Fastify Error handlers - DEV Community ‍ ‍
Validation errors appear when the submitted data from a client doesn't match the endpoint's JSON schema; 404 errors when the requested route ...
Read more >
Better Error Handling In NodeJS With Error Classes
Kelvin Omereshone explains the error class pattern and how to use it for a better, more efficient way of handling errors across your ......
Read more >
Fastify: How to have public and private routes? - Stack Overflow
addHook("preHandler", async (req, reply) => { if (!req.user) { throw new Error("Must be logged in"); } }); }; module.exports = fp(plugin, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found