Handling Http errors in coffeescript

2019-09-06 13:38发布

问题:

I am trying to handle a http request in coffeescript, but in case the server is down the app just dies with error below, and I can't find the right solution.

Code:

 http.get "http://localhost:8080/health", (res) ->
        status =  res.statusCode
        value = if status == 200 then 1 else 0
        console.log value
        server.push_metric metricPrefix , value
        res.on 'error', () ->
          colsone.log "Tomcat Disconected"

error:

events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: connect ECONNREFUSED
    at errnoException (net.js:770:11)
    at Object.afterConnect [as oncomplete] (net.js:761:19)

回答1:

I think you have to actively listen for the error in a separate event handler. Right now, you're attaching an event handler to the response (res), but it needs to be attached to the request object itself. See the docs.

req = http.get "http://localhost:8080/health", (res) ->
  status = res.statusCode
  value = if status == 200 then 1 else 0
  console.log value
  server.push_metric metricPrefix , value

req.on 'error', ->
  console.log "Tomcat Disconected"

Also, you have a typo in your current error handler: colsone.log