Last Updated: September 29, 2021
·
414
· nanotime

Always return the statements in coffeescript express responses

I was stucked with an issue for days, jesus that's not funny.

Normally when you work with Express you are always sending responses, in json, or rendering, or whatever.

That can create some issues if you don't cut the responses at the moment when they are sent...

Look at this code:

User.findById(body._id)
      .exec (err, user) ->
        if err then res.json new Internal(err.message, err.stack)
        if user then res.json new Forbidden("#{user._id} ya existe")

        User.create body, (err, newUser) ->
          if err then res.json new Internal(err.message, err.stack)

          res.json new Ok(newUser, "#{newUser._id} creado"

Don't care about the outputs, did you see the problem in that code? ... Yes! if an error is fired, or the statment are not found it will be sent and you'll be prompted with the rigth message, BUT for sure in the console your server gonna be stopped with some message like:

Error, can't set headers after they are sent

pandemonium, running in cirlces around the computer

The reason is simple, you are sending two responses, first the error/404 and then, the code try to send an OkResponse, that's not really a good thing.

¿Solution?

Yep, just return the responses explicitly, like:

User.findById(body._id)
      .exec (err, user) ->

        if err 
          return res.json new Internal(err.message, err.stack)
        if user 
          return res.json new Forbidden("#{user._id} ya existe")

        User.create body, (err, newUser) ->
          if err 
            return res.json new Internal(err.message, err.stack)

          res.json new Ok(newUser, "#{newUser._id} creado")

The cleanest code ever? Nope, but good enough, and it works.

I hope to be helpful for someone <3