📖 Scenario: You are building a simple Deno script that reads user data from a JSON file. Sometimes the file might be missing or contain invalid data. You want to handle these errors gracefully and log useful messages to understand what went wrong.
🎯 Goal: Create a Deno script that reads a JSON file named user.json, handles errors if the file is missing or the JSON is invalid, and logs messages for success or failure.
📋 What You'll Learn
Create a variable to hold the filename user.json
Add a variable to hold a logger prefix string
Use a try-catch block to read and parse the JSON file
Log success or error messages with the prefix
Print the parsed user data if successful
💡 Why This Matters
🌍 Real World
Handling errors and logging is essential in real-world scripts and applications to avoid crashes and to understand issues quickly.
💼 Career
DevOps engineers and developers must write robust scripts that handle failures gracefully and provide clear logs for troubleshooting.
Progress0 / 4 steps
1
Setup filename variable
Create a variable called filename and set it to the string "user.json".
Deno
Hint
Use const filename = "user.json"; to store the file name.
2
Add logger prefix
Add a variable called logPrefix and set it to the string "[UserLoader]".
Deno
Hint
Use const logPrefix = "[UserLoader]"; to create a prefix for log messages.
3
Read and parse JSON with error handling
Use a try-catch block to read the file filename using Deno.readTextFile, parse it with JSON.parse, and store the result in a variable called userData. In the catch block, log an error message using console.error with the logPrefix and the error message.
Deno
Hint
Use try { const text = await Deno.readTextFile(filename); userData = JSON.parse(text); } and catch (error) { console.error(`${logPrefix} Error loading user data: ${error.message}`); }.
4
Print the user data
Add a console.log statement to print the variable userData.
Deno
Hint
Use console.log(userData); to display the loaded data.
Practice
(1/5)
1. What is the main purpose of using try...catch in Deno?
easy
A. To handle errors and keep the program running smoothly
B. To speed up the program execution
C. To create new files automatically
D. To log messages to the console
Solution
Step 1: Understand the role of try...catch
The try...catch block is used to catch errors that happen during program execution.
Step 2: Identify the effect on program flow
By catching errors, the program can handle them gracefully and continue running instead of crashing.
Final Answer:
To handle errors and keep the program running smoothly -> Option A
Quick Check:
Error handling = To handle errors and keep the program running smoothly [OK]
Hint: Try...catch blocks catch errors to prevent crashes [OK]
Common Mistakes:
Thinking try...catch speeds up code
Confusing error handling with logging
Believing try...catch creates files
2. Which of the following is the correct syntax to log an error message in Deno?
easy
A. console.log.error('An error occurred')
B. console.error('An error occurred')
C. console.err('An error occurred')
D. console.errorMessage('An error occurred')
Solution
Step 1: Recall the console methods in Deno
Deno uses standard JavaScript console methods like console.error() to log error messages.
Step 2: Check each option's syntax
Only console.error('An error occurred') is valid syntax for logging errors.
The code throws an error with message 'Oops!'. The catch block catches it and accesses e.message.
Step 2: Analyze the console.log output
The catch block logs 'Caught:' followed by the error message, so output is 'Caught: Oops!'.
Final Answer:
Caught: Oops! -> Option A
Quick Check:
Catch logs error message = Caught: Oops! [OK]
Hint: Catch block logs error.message after throw [OK]
Common Mistakes:
Expecting full error object printed
Confusing error message with undefined
Thinking no output occurs
4. Identify the error in this Deno code snippet:
try {
const data = JSON.parse('{ bad json }')
} catch {
console.log('Parsing failed', e.message)
}
medium
A. console.log should be console.error
B. JSON.parse syntax is correct
C. Missing error parameter in catch block
D. try block should not have code
Solution
Step 1: Check catch block syntax
In Deno (and modern JavaScript), catch block can omit error parameter, but to access error details, it must be declared.
Step 2: Identify the problem with missing error parameter
The code tries to catch error but does not declare error variable, so error details can't be accessed if needed.
Final Answer:
Missing error parameter in catch block -> Option C
Quick Check:
Catch needs error param to access error = Missing error parameter in catch block [OK]
Hint: Always include error param in catch to access error info [OK]
Common Mistakes:
Assuming catch() always requires error param
Thinking console.log is wrong for errors
Believing try block can't have code
5. You want to log an error with a timestamp and the error message in Deno. Which code snippet correctly does this?
hard
A. try {
throw new Error('Fail')
} catch (e) {
console.log('Error:', e)
}
B. try {
throw new Error('Fail')
} catch (e) {
console.error(e)
console.log(new Date())
}
C. try {
throw new Error('Fail')
} catch {
console.error('Error occurred')
}
D. try {
throw new Error('Fail')
} catch (e) {
console.error(`[${new Date().toISOString()}] Error: ${e.message}`)
}
Solution
Step 1: Understand the requirement for timestamp and message
The log must include current time in ISO format and the error message.
Step 2: Check each option for correct formatting
try {
throw new Error('Fail')
} catch (e) {
console.error(`[${new Date().toISOString()}] Error: ${e.message}`)
} uses template literals to combine timestamp and error message in one console.error call, which is correct.
Final Answer:
try {
throw new Error('Fail')
} catch (e) {
console.error(`[${new Date().toISOString()}] Error: ${e.message}`)
} -> Option D
Quick Check:
Timestamp + error message in one log = try {
throw new Error('Fail')
} catch (e) {
console.error(`[${new Date().toISOString()}] Error: ${e.message}`)
} [OK]
Hint: Use template literals with new Date().toISOString() for timestamps [OK]
Common Mistakes:
Logging error and timestamp separately
Missing error parameter in catch
Using console.log instead of console.error for errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.