Handling Http errors in coffeescript

夙愿已清 提交于 2019-12-11 14:56:25

问题


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



来源:https://stackoverflow.com/questions/15906635/handling-http-errors-in-coffeescript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!