Skip to content

Error

Source: shiva-fw/libs/errors/init.lua

Structured error factory. Every shiva error carries a dot-notation code, a human-readable message, optional context key-value pairs, a suggestion for the developer, a severity level, a timestamp, and a stack trace.

Availability

Error is a global in every shiva module (loaded by sh_init.lua). No import required.

Error Levels

lua
Error.DEBUG    -- 'debug'
Error.INFO     -- 'info'
Error.WARNING  -- 'warning'
Error.ERROR    -- 'error'   (default)
Error.CRITICAL -- 'critical'
Error.FATAL    -- 'fatal'

Methods

Error.new(code, message, context?, suggestion?, level?)

Create a structured error.

lua
local err = Error.new(
    'economy.insufficient',
    'Player does not have enough cash',
    { required = 500, available = 100 },
    'Check balance before calling transferMoney()',
    Error.ERROR
)

Error.format(err, verbose?)

Format an error as a human-readable string. Pass verbose = true to include the stack trace.

lua
print(Error.format(err))
print(Error.format(err, true))  -- with stack trace

Error.safe(fn, errorContext?)

Call fn and return result, nil on success, or nil, ShivaError on failure.

lua
local result, err = Error.safe(function()
    return EconomyService.transferMoney(src, dst, amount)
end, { src = src, amount = amount })

if err then
    Log.logError('economy', err)
end

Error.safeCall(fn, args?, errorContext?)

Like Error.safe but passes args as the argument list to fn.

lua
local result, err = Error.safeCall(myFn, { arg1, arg2 }, { module = 'economy' })

Error.validateConfig(moduleName, config, schema)

Validate a config table against a schema. Returns valid and an array of ShivaError for each failure.

lua
local ok, errs = Error.validateConfig('shiva-fishing', Config, {
    maxCatch  = { type = 'number', min = 1, max = 100 },
    spawnRate = { type = 'number', default = 0.5 },
})
if not ok then
    for _, e in ipairs(errs) do Log.logError('config', e) end
end

Error.isError(value)

Return true if value is a ShivaError table.

lua
if Error.isError(result) then ... end

The ShivaError shape

lua
---@class ShivaError
---@field code       string                  Dot-notation code, e.g. 'economy.insufficient'
---@field message    string                  Human-readable message
---@field context    table<string, any>      Key-value pairs of relevant data
---@field suggestion string                  How the developer should fix this
---@field level      string                  One of the Error.* level constants
---@field timestamp  integer                 Unix timestamp (os.time())
---@field trace      string                  Stack trace string

Released under the MIT License.