How does error function work?

I don’t understand what does the second parameter (level) do. Does it change traceback?
When I use error("test") I get this:

error("test"):1: test
Stack Begin
Script 'error("test")', Line 1  -  Studio
Stack End

And when I use error("test", 2) I get this:

test
Stack Begin
Script 'error("test")', Line 1  -  Studio
Stack End

But didn’t I supposed to get something like this:

test
Stack Begin
Stack End

The level paramater controls where the error will point to in the call stack. A level of 1 (default) will point to the callsite of error itself, 2 will point to the function that called the callsite and so on.

local function myErroringFunction()
    error("this is an error", 2)
end

local function myOtherFunction()
    myErroringFunction()
end

myOtherFunction()

The error thrown will point to the line in myOtherFunction where it calls myErroringFunction because the level is 2.

2 Likes

Oh that’s nifty. I assume that’s for things like making public modules, where you want to throw an error when someone calls your function with the wrong arguments?

Yes, this is mostly what it is used for, very helpful for debugging.

2 Likes

It doesn’t work and idk why:

ServerScriptService.Script:10: this is an error  -  Server - Script:2
Stack Begin  -  Studio
Script 'ServerScriptService.Script', Line 2 - function myErroringFunction  -  Studio - Script:6
Script 'ServerScriptService.Script', Line 6 - function myOtherFunction  -  Studio - Script:10
Script 'ServerScriptService.Script', Line 9  -  Studio - Script:9
Stack End

That’s exactly what it’s supposed to do.

1 Like

It’s erroring, as it’s supposed to do…

But why it doesn’t look like this:

Stack Begin  -  Studio
Script 'ServerScriptService.Script', Line 6 - function myOtherFunction  -  Studio - Script:10
Script 'ServerScriptService.Script', Line 9  -  Studio - Script:9
Stack End```
local function myErroringFunction(): ()
    error("This is an error.", 2)
end

local function myOtherFunction(): ()
    myErroringFunction()
end

myOtherFunction()

This spits out…

  Players.Sepruko.PlayerScripts.LocalScript:6: This is an error.  -  Client - LocalScript:2
  Stack Begin  -  Studio
  Script 'Players.Sepruko.PlayerScripts.LocalScript', Line 2 - function myErroringFunction  -  Studio - LocalScript:2
  Script 'Players.Sepruko.PlayerScripts.LocalScript', Line 6 - function myOtherFunction  -  Studio - LocalScript:6
  Script 'Players.Sepruko.PlayerScripts.LocalScript', Line 9  -  Studio - LocalScript:9
  Stack End  -  Studio

The actual error message (Players.Sepruko.PlayerScripts.LocalScript:6: This is an error.) contains where the level parameter points to, line 6, which is correct.

image

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.