Report expected failures at application boundaries
Quick answer
An error boundary translates failures into a documented outcome at an appropriate layer. Expected invalid input can become a tagged result, while unexpected exceptions remain available for diagnosis.
How it works
Catch only the operation whose failure you can handle. For parsing JSON, catch SyntaxError from the parse itself, then validate shape separately. In an async boundary, await a promise inside try if you need to catch its rejection there. Do not turn every programming error into a success or lose its cause. Return stable public reasons, record narrow diagnostics privately, and ensure cleanup with finally where needed. This is a general application pattern, not a framework-specific error boundary.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {function read(text){let x;try{x=JSON.parse(text);}catch(e){if(e instanceof SyntaxError)return "syntax";throw e;}return Number.isInteger(x?.qty)?"ok":"shape";}console.log(read("{"),read("{}"),read(JSON.stringify({qty:2})));})()Expected console output:
syntax shape okInvalid syntax and invalid application data have different outcomes.
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {async function run(work){try{return await work();}catch{return "failed";}}console.log(await run(()=>Promise.reject(new Error("x"))),await run(()=>Promise.resolve("ok")));})()Expected console output:
failed okThe catch handles the awaited rejection.
Common mistakes
Do not return an unawaited promise from try when intending to translate its asynchronous rejection in the local catch.
Practice
Design public failure tags for invalid JSON and invalid shape, then test the successful and rejected paths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Report expected failures at application boundaries — Knowledge Check
Apply the concept and reason about local example output.
What should be separated after successfully parsing JSON?
Why await a promise inside the local try block?
What should an unexpected error normally retain?
What is the exact console output in Report expected failures at application boundaries example 1?
(async () => {function read(text){let x;try{x=JSON.parse(text);}catch(e){if(e instanceof SyntaxError)return "syntax";throw e;}return Number.isInteger(x?.qty)?"ok":"shape";}console.log(read("{"),read("{}"),read(JSON.stringify({qty:2})));})()What is the exact console output in Report expected failures at application boundaries example 2?
(async () => {async function run(work){try{return await work();}catch{return "failed";}}console.log(await run(()=>Promise.reject(new Error("x"))),await run(()=>Promise.resolve("ok")));})()