How to read only the error message from the pcall?

Let’s say I create an error inside of a pcall function.

local success, err = pcall(function()
	error("Failed to add")
end)
print(success, err)

How can I retrieve only "Failed to add" and nothing else without manipulating the string? Because currently if I print the err message, it will give me the script location and line number, as follows:

false, "Workspace.Script:2: Failed to add"

The reason I want the error message only without the extra information is that I want to show the error message to the players. For example error("Not enough diamonds to buy this item").

I could technically trim the error message but that would require string manipulation, and it’s not guaranteed that the format of the error message will not change somewhere in the future unexpectedly.

local errMSG

local success, err = pcall(function()
	errMSG = "er"
end)

if errMSG then
error(errMSG)
end

I don’t think this is possible (without string manipulation), but it can be done with SUPER EASY string manipulation:

local function onlyErr(err)
    return err:split(": ")[2]
end

local success, err = pcall(function()
	error("Failed to add")
end)
print(success, onlyErr(err))
1 Like

That’s not really what I was looking for, I am already doing something similar by returning an object with error message, but it would be more convenient and cleaner for me to just use error() as it would be more clear that it’s an error. Thanks for the suggestion either way.

Use error("Failed to add", 0)

error uses the following arguments: error ( string message, int level = 1 )

The default level of 1 is passing the additional information that you do not need.

4 Likes