Reputation: 6652
With ActionCable, how can I respond with an error after receiving data from a client?
For example, when the client fails to authenticate, ActionCable throws UnauthorizedError
which responds with a 404. I want to respond with a 422, for example, when the data that the client sent is invalid.
Upvotes: 0
Views: 1743
Reputation: 4524
From what I could gather there's no "Rails way" to do this, the answer given by @Viktor seems correct. In summary: ensure all messages are broadcasted with both data and code, then switch by code in the client.
For a more modern and ES6 example see below:
In 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
In 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)
}
}
})
Upvotes: 1
Reputation: 4346
ActionCable.server.broadcast "your_channel", message: {data: data, code: 422}
Then in your.coffee
file:
received: (res) ->
switch res.code
when 200
# your success code
# use res.data to access your data message
when 422
# your error handler
Upvotes: 2