【问题标题】:ActionCable - Respond With ErrorActionCable - 响应错误
【发布时间】:2016-10-04 19:15:08
【问题描述】:

使用 ActionCable,我如何在从客户端接收数据后以错误响应?

例如,当客户端无法通过身份验证时,ActionCable 会抛出UnauthorizedError,它会以 404 响应。我想以 422 响应,例如,当客户端发送的数据无效时。

【问题讨论】:

标签: ruby-on-rails actioncable


【解决方案1】:
ActionCable.server.broadcast "your_channel", message: {data: data, code: 422}

然后在your.coffee文件中:

received: (res) ->
  switch res.code
    when 200
      # your success code
      # use res.data to access your data message
    when 422
      # your error handler

【讨论】:

    【解决方案2】:

    据我所知,没有“Rails 方式”可以做到这一点,@Viktor 给出的答案似乎是正确的。综上所述:保证所有消息都广播有数据和代码,然后在客户端通过代码切换。

    有关更现代的 ES6 示例,请参见下文:

    在轨道上:

    require 'json/add/exception'
    
    def do_work
      // Do work or raise
      CampaignChannel.broadcast_to(@campaign, data: @campaign.as_json, code: 200)
    rescue StandardError => e
      CampaignChannel.broadcast_to(@campaign, data: e.to_json, code: 422) # Actually transmitting the entire stacktrace is a bad idea!
    end
    

    在 ES6 中:

    campaignChannel = this.cable.subscriptions.create({ channel: "CampaignChannel", id: campaignId }, {
      received: (response) => {
        const { code, data } = response
    
        switch (code) {
          case 200:
            console.log(data)
            break
          default:
            console.error(data)
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 2019-05-03
      • 2017-10-02
      • 2017-01-10
      • 2018-05-28
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多