0 day streak
javascript / beginner
Snippet

Parsing JSON Configuration with Try Catch in Vue

The try...catch statement marks a block of statements to try and specifies a response should an exception be thrown. When parsing user-supplied JSON text with JSON.parse(), catching errors prevents application crashes and allows setting a user-friendly error message in reactive state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ref } from 'vue';
export default {
setup() {
const rawInput = ref('{"theme": "dark"}');
const parsedConfig = ref(null);
const errorMessage = ref('');
function parseInput() {
try {
errorMessage.value = '';
parsedConfig.value = JSON.parse(rawInput.value);
} catch (err) {
errorMessage.value = 'Invalid JSON format';
}
}
return { rawInput, parsedConfig, errorMessage, parseInput };
}
};
vue
Breakdown
1
try {
Begins a protected block where runtime errors can be caught without crashing the component.
2
parsedConfig.value = JSON.parse(rawInput.value);
Attempts to parse the input string into a JavaScript object.
3
} catch (err) {
Catches any syntax errors thrown during the parsing process.
4
errorMessage.value = 'Invalid JSON format';
Updates the reactive error message to notify the user of the invalid format.