【问题标题】:Github node action http errors always fails jobGithub 节点操作 http 错误总是导致作业失败
【发布时间】:2021-01-27 06:52:20
【问题描述】:

我有一个看起来像这样的 github 操作:

const http = require('http');
const core = require('@actions/core');


const options = {
    hostname: 'mydomain.com',
    port: 80,
    path: '/webhook',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
};

const postData = {
    foo: 'bar'
}

try {
    
    const strPostData = querystring.stringify(postData);
    options.headers['Content-Length'] = Buffer.byteLength(strPostData);

    const req = http.request(options)
    req.write(strPostData)
    req.end()

} catch (error) {
    core.info(error.message);
}

如果mydomain.com/webhook 离线,我的作业在此操作上失败,记录:

events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED xxx.xxx.xxx.xxx:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketErrorListener (_http_client.js:406:9)
    at Socket.emit (events.js:210:5)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) ***
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: 'xxx.xxx.xxx.xxx',
  port: 80
***

为什么会失败,为什么try catch 没有捕捉到这个?

如果此操作失败,我不希望整个作业都失败,那么如何捕获此失败并将其隐藏在 GitHub 运行器中?

【问题讨论】:

  • 我相信错误是异步的,你需要监听像'error' 这样的事件来捕捉它。另外我注意到您在发送数据之前没有等待连接请求,我不确定您是否这样做。

标签: github-actions


【解决方案1】:

您需要收听'error' 事件才能捕捉到这一点

const strPostData = querystring.stringify(postData);
options.headers['Content-Length'] = Buffer.byteLength(strPostData);

const req = http.request(options)

req.on('error', (err) => {/*Error Caught*/})

req.write(strPostData)
req.end()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 2021-11-08
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2023-01-05
    • 2017-10-18
    • 2023-01-24
    相关资源
    最近更新 更多