tweak(callback): error handling

Errors during callbacks will never respond, so we'll use a protected call
and format the error message with a normal print to keep the thread
alive.
This commit is contained in:
Linden
2022-08-25 18:49:07 +10:00
parent 2391ffa8a7
commit 2a1815c460
2 changed files with 34 additions and 6 deletions

View File

@@ -47,10 +47,10 @@ local function triggerServerCallback(_, event, delay, cb, ...)
events[key] = nil
if promise then
return promise:resolve(response)
return promise:resolve(response or {})
end
return cb and cb(table.unpack(response))
return cb and cb(table.unpack(response or {}))
end
if promise then
@@ -70,12 +70,26 @@ function callback.await(event, delay, ...)
return triggerServerCallback(_, event, delay, false, ...)
end
local function callbackResponse(success, result, ...)
if not success then
if result then
return print(('^1SCRIPT ERROR: %s^0\n%s'):format(result , Citizen.InvokeNative(`FORMAT_STACK_TRACE` & 0xFFFFFFFF, nil, 0, Citizen.ResultAsString()) or ''))
end
return false
end
return { result, ... }
end
local pcall = pcall
---@param name string
---@param cb function
--- Registers an event handler and callback function to respond to server requests.
function callback.register(name, cb)
RegisterNetEvent(cbEvent:format(name), function(resource, key, ...)
TriggerServerEvent(cbEvent:format(resource), key, { cb(...) })
TriggerServerEvent(cbEvent:format(resource), key, callbackResponse(pcall(cb, ...)))
end)
end

View File

@@ -28,10 +28,10 @@ local function triggerClientCallback(_, event, playerId, cb, ...)
events[key] = nil
if promise then
return promise:resolve(response)
return promise:resolve(response or {})
end
return cb and cb(table.unpack(response))
return cb and cb(table.unpack(response or {}))
end
if promise then
@@ -51,12 +51,26 @@ function callback.await(event, playerId, ...)
return triggerClientCallback(_, event, playerId, false, ...)
end
local function callbackResponse(success, result, ...)
if not success then
if result then
return print(('^1SCRIPT ERROR: %s^0\n%s'):format(result , Citizen.InvokeNative(`FORMAT_STACK_TRACE` & 0xFFFFFFFF, nil, 0, Citizen.ResultAsString()) or ''))
end
return false
end
return { result, ... }
end
local pcall = pcall
---@param name string
---@param cb function
--- Registers an event handler and callback function to respond to client requests.
function callback.register(name, cb)
RegisterNetEvent(cbEvent:format(name), function(resource, key, ...)
TriggerClientEvent(cbEvent:format(resource), source, key, { cb(source, ...) })
TriggerClientEvent(cbEvent:format(resource), source, key, callbackResponse(pcall(cb, source, ...)))
end)
end