You should only use pcalls when you’re creating a function or sending a request that can possibly error. For example, if you send a web request to your personal servers on your website, that could possibly fail for whatever reason. People usually use pcalls so they can create a “backup” when something fails.
local HttpService = game:GetService("HttpService")
local function request()
local response = HttpService:RequestAsync(
{
Url = "http://httpbin.org/post", -- This website helps debug HTTP requests
Method = "POST",
Headers = {
["Content-Type"] = "application/json" -- When sending JSON, set this!
},
Body = HttpService:JSONEncode({hello = "world"})
}
)
-- Inspect the response table
if response.Success then
print("Status code:", response.StatusCode, response.StatusMessage)
print("Response body:\n", response.Body)
else
print("The request failed:", response.StatusCode, response.StatusMessage)
end
end
-- Remember to wrap the function in a 'pcall' to prevent the script from breaking if the request fails
local success, message = pcall(request)
if not success then
print("Http Request failed:", message)
end
The code above sends an Http request to an external website. The pcall is there so that the rest of the script doesn’t break if the request fails.
You really shouldn’t put yourself in a position where need to use a lot of pcalls unless absolutely necessary.
For a Roblox function, whenever you see “Async,” that typically means that it’s gonna do an external web call and you should wrap it in a pcall.
Only when required. If something has a chance of provoking an error, such as getting save data, http requests, etc., I use pcall. There shouldn’t be any other cases for using pcall.