Detect whether a players avatar has loaded in

Hey, I am currently creating a simple search script that grabs a players avatar and places it in an image label.

function search()
	local player = script.Parent.Text
	local frame = script.Parent.Parent.userDetails
	
	frame.avatar.Image = ("http://www.roblox.com/Thumbs/Avatar.ashx?x=100&y=100&Format=Png&username=%s"):format(player)
end

If the player’s avatar can’t be found is there a way to detect this so I can display the error message in the actual game rather than just the output box?

Thanks for your help.

Well you can use pcall() for this. pcall which littearly stands for Protected Call, is used to prevent errors from showing up. So if there was a part of code that would error for some reason, pcall will stop that error from happening without stoping the script or causing any problems, and in addition, pcall returns a boolean value determining wether the part of code ran successfully or not (if it didn’t error it returns true, if it did it returns false) and the part that interests you, it also returns the error message that was supposed to pop up in the output.

So here is an example using pcall

pcall(function() --the part of code that you wanna prevent from erroring, has to be inside of a function
game.Workspace.Part.BrickColor = BrickColor.new("Really Red")
end)

If the Part doesn’t exist, this function will obviously error, but with pcall, you can see that nothing happens and no error was logged in the output.
To use the two pieces of information pcall returns you gotta do something like this.
success would be wether it functioned or no, reason is the error message

local success, reason = pcall(function() 
game.Workspace.Part.BrickColor = BrickColor.new("Really Red")
end)

if success = true then --if exectued
   print("function successfully ran")
elseif success == false then --if errored
   print("function didn't want run as intended, reason:", reason) --we would print the error message here
end


And yeah! That’s it, more documentation here

2 Likes

Thank you for the explanation! :smiley:

1 Like

A dedicated function exists to get an avatar’s thumbnail, GetUserThumbnailAsync. This should be used over the image endpoint. Not only does it supply the avatar thumbnail, but it also supplies a success boolean to tell you if the image is ready to be used or not.

1 Like

Alrighty. Thank you for the alternative. I would rather run a dedicated function than get it straight from the API.