Pcall does not catch error in UpdateAsync

It seems pcall does not catch errors inside Updateasyncs second argument function.

I thought I could use pcall to catch any error that occures inside it but apparently not.
Here’s my code:

local success, err = pcall(function()
	local DataStore = game:GetService("DataStoreService"):GetDataStore("test")

	local data = DataStore:UpdateAsync("Data", function(oldData)
		local newData = oldData or {}

		for name, value in pairs(nil) do --This will cause an error
		end

		return newData
	end)
end)

print("Complete:",success, err)

Here’s the output (removed timestamps):

ServerScriptService.Script:7: invalid argument #1 to ‘pairs’ (table expected, got nil) - Server - Script:7
Stack Begin - Studio
Script ‘ServerScriptService.Script’, Line 7 - Studio - Script:7
Stack End - Studio
Transform function error ServerScriptService.Script:7: invalid argument #1 to ‘pairs’ (table expected, got nil) - Studio
Complete: true nil - Server - Script:15

As you can see the pcall returns true even though an error has occured within it.
This must be a bug right? It’s suppose to catch all errors inside it, correct?

1 Like

Thats because the function in the updateAsync runs in another thread.

local succ, err = pcall(function()
	spawn(function()
		return 1 + nil
	end)
end)

print(succ, err)

Output:

true, nil
ServerScriptService.Script:3: attempt to perform arithmetic (add) on number and nil
1 Like

So I’m supposed to have another pcall inside updateasync?
Why even have a pcall outside it then?

I think inside is a good idea.

But I dont think you need a pcall inside.

You shouldn’t ever have the possibility to error in UpdateAsync as the function likely has the chance to yield. (Nothing in UpdateAsync can yield)

the pcall outside is for the UpdateAsync itself and not what is contained within it. If for some reason it could not obtain data from DataStore, it would time out and error. This is because you are getting information from service that is not part of the game itself. This is also why you pcall all other services that fetch data outside the game environment, like Marketplace.

Also don’t put a pcall in the UpdateAsync as it should not yield. If you need it to yield, use GetAsync, do the stuff, then SetAsync when done.