使用ActionCable,如何在从客户端接收数据后响应错误?
例如,当客户端身份验证失败时,ActionCable抛出UnauthorizedError,后者以404作为响应。例如,当客户端发送的数据无效时,我希望使用422进行响应。
发布于 2016-10-30 18:43:33
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发布于 2018-12-12 23:42:33
据我所知,没有"Rails方法“可以做到这一点,@Viktor给出的答案似乎是正确的。总结:确保所有消息都是带数据和带代码的广播,然后在客户端按代码切换。
有关更现代的ES6示例,请参见以下内容:
在rails中:
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)
}
}
})https://stackoverflow.com/questions/39860053
复制相似问题