Recently I noticed that the server selection menu in my game stopped working. A quick look in the dev console showed this:
This is not a custom error() function or anything, but oddly enough its in all lowercase and in quotes.
Code:
local ms = game:GetService("MessagingService")
game.ReplicatedStorage.Events.Servers.GetServers.OnServerEvent:Connect(function(plr, nam)
local data = {target = plr.Name, place = nam}
ms:PublishAsync(nam.." Server Get", data) -- this line errors
end)
How can I fix this and in what conditions does this happen? I havent seen it anywhere before.
Because this is a Lua error, you can wrap the call to PublishAsync in a pcall (protected call) and perform different logic in the case of an error, for example, you could implement some kind of fall-off retry pattern if this were critical to your game.
Here’s a really quick stab at what that might look like:
local MessagingService = game:GetService("MessagingService")
function tryPublish(topic, message)
-- This is 4 attempts: immediate, delay 5 seconds, 10 seconds, 20 seconds
local retry = 0, attemptDelays = {5, 10, 20}
local success, errorMessage
while retry <= #attemptDelays do
if retry > 0 then wait(attemptDelays[retry]) end
success, errorMessage = pcall(function()
return MessagingService:PublishAsync(topic, message)
end)
if success then
return true
end
retry = retry + 1
end
-- out of attempts
return false, errorMessage
end
-- Now you can use tryPublish(topic, message) to attempt to publish 4 times with exponential
-- falloff over 35+ seconds. Also, you can check the result returned and do something
-- with the message
Note that the example for cross-server messaging includes a pcall, but doesn’t really do anything sophisticated with it.
Asynchronous methods exist to deal with long-running tasks. They may be for long-running computations like path finding happening on another CPU thread or GPU device, or I/O to player devices or network communication. They can fail for many, many reasons - network issues, service outages, timeouts, misconfigurations, etc. It’s not random, but at the same time, failure is not predictable. If you depend on an async task, you need to have a plan for what to do when it fails or it will error and that will propagate until it is caught by a pcall or the message is dumped to the output / log.