javascript / beginner
Snippet
Safely Parsing User Configuration with Try Catch in Vue
JSON.parse throws a synchronous SyntaxError when parsing invalid JSON strings. Wrapping this operation in a try...catch block catches the error and assigns a friendly message to a reactive Vue reference without crashing the component.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { ref } from 'vue';export default {setup() {const config = ref(null);const errorMessage = ref('');function parseConfigString(rawJson) {try {errorMessage.value = '';config.value = JSON.parse(rawJson);} catch (err) {errorMessage.value = 'Invalid JSON configuration: ' + err.message;}}return { config, errorMessage, parseConfigString };}};
vue
Breakdown
1
try {
Begins a protected execution block for operations that may throw errors.
2
config.value = JSON.parse(rawJson);
Parses the incoming JSON string into a JavaScript object.
3
} catch (err) {
Executes only if JSON.parse fails, receiving the error object for error handling.