Using `pcall` to make your config more stable

· Nano Tips for Vim

#config

This post is an edited version of a response I left to a user being frustrated that their config regularly breaks.

any small change in the massive config will suddenly break everything
– user on reddit

I found wrapping every require in my init.lua in a pcall did help with this problem.

pcall works roughly like try & catch in other languages. Normally, a script will stop execution when it runs into an error, so an error in one of the early required modules will prevent all the modules required afterwards from bring loaded.

1-- init.lua
2require("config.options")
3require("config.autocmds") -- <- error here
4require("config.theme-config") -- <- not loaded
5require("config.keybindings") -- <- not loaded

With pcall, the script will continue execution even if it encounters an error, so a problem in one of your modules does not prevent the following ones from being loaded. This way, when you make a mistake in one of your config files, the other ones are still loaded correctly. Any configuration error will stay isolated and will not cascade into a completely broken configuration:

 1-- init.lua
 2local function safeRequire(module)
 3	local success, loadedModule = pcall(require, module)
 4	if success then return loadedModule end
 5	vim.cmd.echo ("Error loading " .. module)
 6end
 7
 8safeRequire("config.options")
 9safeRequire("config.autocmds") -- <- error here
10safeRequire("config.theme-config") -- <- still loaded
11safeRequire("config.keybindings") -- <- still loaded

Of course, splitting up your config into smaller modules further insulates your modules from issues in other parts of your config. (Apart from being good practice anyway.)