📖 Scenario: You are building a simple Svelte app that fetches data from an API. You want to create helper functions to handle JSON responses and errors cleanly.
🎯 Goal: Build two helper functions: json to format JSON responses and error to create error responses. Use these helpers in a Svelte component to show success or error messages.
📋 What You'll Learn
Create a json helper function that returns an object with status and body properties.
Create an error helper function that returns an object with status and body containing an error message.
Use these helpers in a Svelte component to display a success message or an error message based on a simulated API call.
Follow Svelte syntax and patterns for reactive variables and event handling.
💡 Why This Matters
🌍 Real World
Creating helper functions to standardize API responses helps keep frontend code clean and consistent when handling data and errors.
💼 Career
Understanding how to handle JSON and error responses is essential for frontend developers working with APIs and building interactive web apps.
Progress0 / 4 steps
1
Create the json helper function
Create a function called json that takes two parameters: data and status. It should return an object with status set to the passed status and body set to the passed data.
Svelte
Hint
Think of json as a way to package data with a status code.
2
Create the error helper function
Create a function called error that takes two parameters: status and message. It should return an object with status set to the passed status and body set to an object with a message property containing the passed message.
Svelte
Hint
The error function packages an error message with a status code.
3
Set up Svelte component state variables
In a Svelte component, create two reactive variables: response initialized to null and errorMessage initialized to an empty string ''.
Svelte
Hint
Use let to declare reactive variables in Svelte.
4
Add a function to simulate API call and display response
Add a function called fetchData inside the <script> tag. It should simulate a successful API call by setting response to the result of json({ message: 'Success!' }, 200) and clear errorMessage. Also add a button in the markup that calls fetchData on click. Below the button, display response.body.message if response exists, or errorMessage if it is not empty.
Svelte
Hint
Use Svelte's on:click event to call fetchData.
Practice
(1/5)
1. What is the main purpose of the json() helper in SvelteKit server endpoints?
easy
A. To parse incoming JSON requests
B. To throw an HTTP error with a message
C. To send a JSON response back to the client
D. To redirect the user to another page
Solution
Step 1: Understand the role of json()
The json() helper formats data as a JSON response for the client.
Step 2: Differentiate from other helpers
Unlike error(), which throws HTTP errors, json() sends data successfully.
Final Answer:
To send a JSON response back to the client -> Option C
Passing status as a separate argument without object
Using error() to send success responses
Using Response constructor incorrectly
3. Consider this SvelteKit endpoint code:
import { json, error } from '@sveltejs/kit';
export function GET() {
const data = { user: 'Alice' };
if (!data.user) {
throw error(404, 'User not found');
}
return json(data);
}
What will be the HTTP status code and response if data.user is missing?
medium
A. Status 200 with empty JSON object
B. Status 404 with message 'User not found'
C. Status 500 with server error
D. Status 200 with user data
Solution
Step 1: Analyze the condition
If data.user is missing (falsy), the code throws error(404, 'User not found').
Step 2: Understand error() behavior
The error() helper throws an HTTP error with the given status and message.
Final Answer:
Status 404 with message 'User not found' -> Option B
Quick Check:
Missing user triggers error(404) [OK]
Hint: error() throws HTTP errors with status and message [OK]
Common Mistakes:
Assuming json() runs even if error is thrown
Thinking error() returns JSON data
Confusing status codes for errors
4. Identify the error in this SvelteKit endpoint code snippet:
import { json, error } from '@sveltejs/kit';
export function POST() {
const data = { success: true };
return error(200, 'All good');
}
medium
A. Using error() with status 200 is incorrect
B. Missing return type annotation
C. POST function must be async
D. json() should be used instead of error() to send success
Solution
Step 1: Check status code validity
The error() helper requires status codes 400-599. Using 200 triggers "Non-error status code 200".
Step 2: Correct helper for success
For success (status 200), use json() instead of error().
Final Answer:
Using error() with status 200 is incorrect -> Option A
Quick Check:
Use json() for success, error() for errors [OK]
Hint: error() is for errors, not success responses [OK]
Common Mistakes:
Using error() with 200 status
Not returning json() for success
Assuming error() can send normal data
5. You want to create a SvelteKit endpoint that returns a JSON list of items but throws a 400 error if the list is empty. Which code snippet correctly implements this behavior?
hard
A. export function GET() {
const items = [];
if (items.length === 0) {
throw error(400, 'No items found');
}
return json(items);
}
B. export function GET() {
const items = [];
if (!items) {
return error(400, 'No items found');
}
return json(items);
}
C. export function GET() {
const items = [];
if (items.length === 0) {
return json({ error: 'No items found' }, { status: 400 });
}
return json(items);
}
D. export function GET() {
const items = [];
if (items.length === 0) {
throw json({ error: 'No items found' }, { status: 400 });
}
return json(items);
}
Solution
Step 1: Check error throwing for empty list
export function GET() {
const items = [];
if (items.length === 0) {
throw error(400, 'No items found');
}
return json(items);
} correctly throws error(400, 'No items found') when the list is empty.
Step 2: Validate response for non-empty list
It returns json(items) properly when items exist.
Final Answer:
export function GET() {
const items = [];
if (items.length === 0) {
throw error(400, 'No items found');
}
return json(items);
} -> Option A
Quick Check:
Throw error() for HTTP errors, json() for data [OK]
Hint: Throw error() for bad status, json() for good data [OK]
Common Mistakes:
Returning error() instead of throwing it
Using json() with error status instead of throwing error()
Throwing json() which is invalid
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.