使用ActionCable,如何在从客户端接收数据后回复错误?
例如,当客户端无法进行身份验证时,ActionCable会抛出UnauthorizedError
,并以404响应。我想用422响应,例如,当客户端发送的数据无效时。
答案 0 :(得分: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
答案 1 :(得分:0)
据我所知,没有“ 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)
}
}
})