Handle YAML parse errors in js-yaml
YAML written by people often contains mistakes, so code that loads it should catch errors and report them clearly.
How it works
- Wrap load in try/catch. The README calls
loadinside atryblock with acatchfor errors. The example puts that pattern in a smallsafeLoadhelper. [1] - Compare inputs. The helper runs on several snippets: valid ones print their data, broken ones print the first line of the error message instead of stopping the script. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { load } from 'js-yaml'
function safeLoad(label, text) {
try {
const document = load(text)
console.log('OK ' + label + ' -> ' + JSON.stringify(document))
} catch (e) {
console.log('FAIL ' + label + ' -> ' + e.message.split('\n')[0])
}
}
safeLoad('simple map', 'greeting: hello')
safeLoad('list', '- a\n- b\n- c')
safeLoad('unclosed list', 'items: [1, 2, 3')
safeLoad('bad indent', 'server:\n host: a\n port: 80')
safeLoad('duplicate key', 'name: a\nname: b')
safeLoad('unclosed quote', 'title: "hello')
safeLoad('nested', 'user:\n name: Ada\n tags: [x, y]')
Fix one of the broken snippets and watch it move from the error list to the OK list. Code written by AgentGid [1].
Fix one of the broken snippets and watch it move from the error list to the OK list. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with js-yaml 5.4.3. Needs WebGL.
More js-yaml examples
Parse YAML with js-yaml load() Write YAML with js-yaml dump() Update a YAML config with js-yaml
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.