Skip to content

Commit c02268a

Browse files
committed
feat(plugin): improve error handling and show better error message
1 parent d5686ef commit c02268a

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

lua/lazy/core/plugin.lua

+25-16
Original file line numberDiff line numberDiff line change
@@ -146,52 +146,61 @@ function Spec:import(spec)
146146

147147
local imported = 0
148148

149-
---@type (string|(fun():LazyPluginSpec))[]
149+
---@type {modname: string, load: fun():(LazyPluginSpec?, string?)}[]
150150
local modspecs = {}
151151

152152
if type(import) == "string" then
153153
Util.lsmod(import, function(modname, modpath)
154-
modspecs[#modspecs + 1] = modname
155-
package.preload[modname] = function()
156-
return loadfile(modpath)()
157-
end
154+
modspecs[#modspecs + 1] = {
155+
modname = modname,
156+
load = function()
157+
local mod, err = loadfile(modpath)
158+
if mod then
159+
return mod()
160+
else
161+
return nil, err
162+
end
163+
end,
164+
}
165+
end)
166+
table.sort(modspecs, function(a, b)
167+
return a.modname < b.modname
158168
end)
159-
table.sort(modspecs)
160169
else
161-
modspecs = { spec.import }
170+
modspecs = { modname = import_name, load = spec.import }
162171
end
163172

164173
for _, modspec in ipairs(modspecs) do
165174
imported = imported + 1
166-
local modname = type(modspec) == "string" and modspec or import_name
175+
local modname = modspec.modname
167176
Util.track({ import = modname })
168177
self.importing = modname
169178
-- unload the module so we get a clean slate
170179
---@diagnostic disable-next-line: no-unknown
171180
package.loaded[modname] = nil
172181
Util.try(function()
173-
local mod = type(modspec) == "function" and modspec() or require(modspec)
174-
if type(mod) ~= "table" then
175-
self.importing = nil
182+
local mod, err = modspec.load()
183+
if err then
184+
self:error("Failed to load `" .. modname .. "`:\n" .. err)
185+
elseif type(mod) ~= "table" then
176186
return self:error(
177187
"Invalid spec module: `"
178188
.. modname
179189
.. "`\nExpected a `table` of specs, but a `"
180190
.. type(mod)
181191
.. "` was returned instead"
182192
)
193+
else
194+
self:normalize(mod)
183195
end
184-
self:normalize(mod)
185-
self.importing = nil
186-
Util.track()
187196
end, {
188197
msg = "Failed to load `" .. modname .. "`",
189198
on_error = function(msg)
190199
self:error(msg)
191-
self.importing = nil
192-
Util.track()
193200
end,
194201
})
202+
self.importing = nil
203+
Util.track()
195204
end
196205
if imported == 0 then
197206
self:error("No specs found for module " .. spec.import)

0 commit comments

Comments
 (0)