inversify-express-utils icon indicating copy to clipboard operation
inversify-express-utils copied to clipboard

Can't set headers after they are sent.

Open Natashkinsasha opened this issue 6 years ago • 8 comments

Hi. I decided to try an example. But on the request I get 204 code and an error in the logs. How I understand it before my error handler, some other one works.

@controller('/foo')
class FooController implements interfaces.Controller {
    @httpGet('/')
    private index(req: express.Request, res: express.Response, next: express.NextFunction) {
        return next(new Error());
    }
}
const container = new Container();
const server = new InversifyExpressServer(container);
server.setErrorConfig((app) => {
    app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
        res.status(500).send('Something broke!');
    });
});
const app = server.build();
app.listen(3000);
Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:491:11)
    at ServerResponse.setHeader (_http_outgoing.js:498:3)
    at ServerResponse.header (E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\response.js:767:10)
    at ServerResponse.contentType (E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\response.js:595:15)
    at ServerResponse.send (E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\response.js:145:14)
    at app.use (E:\workplace\wx-meteor-v2\src\index.ts:37:25)
    at Layer.handle_error (E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\router\index.js:315:13)
    at E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (E:\workplace\wx-meteor-v2\node_modules\inversify-express-utils\node_modules\express\lib\router\index.js:335:12)

Natashkinsasha avatar Jan 13 '19 21:01 Natashkinsasha

We are also having this issue. It appears to only affect the last listed method in the controller class.

I have found 2 workarounds but these go against the documentation of calling return next(err);.

Workaround 1 (throw the error, seems a bit pointless try/catch to throw, but you may want to manipulate the error before you send it up):

try {
  const val = await serviceCallAsync();
  res.status(200).send(val);
} catch(err) {
  throw err;
}

Workaround 2 (utilise the Promises):

try {
  const val = await serviceCallAsync();
  Promise.resolve(val);
} catch(err) {
  return Promise.reject(err);
}

We haven't been able to figure out where the problem lies but it could be something to do with the decorators.

nref-dan avatar Jan 25 '19 14:01 nref-dan

@dcavanagh is anyone still maintaining inversify and other subpackages ?

PodaruDragos avatar Oct 01 '19 14:10 PodaruDragos

@PodaruDragos I have very recently been added as maintainer and I am going to start working through the backlog

Jameskmonger avatar Oct 03 '19 08:10 Jameskmonger

Will there be an actual solution? I found that throwing an error works fine but not calling next

sittingbool avatar Nov 24 '19 23:11 sittingbool

I have this issue too.

texiontech avatar May 12 '20 05:05 texiontech

Any update on this? The error handler doesn't seems to be working for me too.

SuspiciousLookingOwl avatar Jul 07 '20 22:07 SuspiciousLookingOwl

I'm having the same issue. I have this configuration to handle some method error with setErrorConfig and sometimes the server responds with status 204 No content, instead of the actual json and status. It always happens with the same endpoint, and with most of the others endpoints works fine, returning the corresponding error status

inversifyServer.setErrorConfig((app) => {
  app.use((err, req, res, _next) => {
    }
    // const jsonResponse ={ ... }
    return res.status(err.status || 500).json(jsonResponse);
  });


@httpPost(
    '/foo',
    'SomeMiddleware',
  )
  async Foo(req: Request, res: Response, next: NextFunction) {
    try {
      // do something
      return res.status(201).json();
    } catch (err) {
      return next(err);
    }
  }

The error in the console is Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client It looks like the response is sent before accessing the setErrorConfig callback.

ctalvarez avatar Sep 06 '20 10:09 ctalvarez

I'm having a super weird issue as well with this...

To give some context,

This is my implementation of overriding the default error handler:

export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
  //We check if the error is coming from our custom error objects.

  if (err instanceof HttpException) {
    return res.status(err?.statusCode).json({
      message: err?.message,
      errorName: err?.name,
      stack: err?.stack,
    });
  }
  //Errors that a unexpected and not handled by our custom errors.
  return res.status(500).json({
    message: err?.message,
    errorName: err?.name,
    stack: err?.stack,
  });

};

I have the following endpoint, let's call it endpoint1

 @httpPost('/refreshAccessToken')
  public async refreshAccessToken(req: Request, res: Response, next: NextFunction): Promise<any> {
    try {
      if (!req.body.refreshToken || !req.body.accessToken || !req.body.id || !req.body.email) {
        throw new BadRequestError('Missing fields')
      }
      return res.status(200).json({status: 200,message: 'Success getting new access token with refresh token.',});
    } catch (error) {
      next(error);
    }
  }

and then just below I have this empty endpoint, let's call this endpoint2.

  @httpPost('')
  public async() {
  }

If I have both endpoint1 and endpoint2, everything works fine, endpoint1 will throw a BadRequestError which will get caught in the catch block and then will be delegated to the errorHandler middleware.

As soon as I remove endpoint2, I get a 204 no-content and the following message:

ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I have no idea what is happening...

Mannydheer avatar Oct 10 '21 14:10 Mannydheer

I confirm the reports from @nref-dan and @Mannydheer The error occurs for the last method listed in the controller.

Would be great to see some updates on this problem

arudenkoofficial avatar Mar 11 '24 10:03 arudenkoofficial