How does the Fetch API work and how do you handle errors?
Suggested answer
fetch(url, options) returns a Promise that resolves with a Response object. Key: fetch only rejects on network failure, not on HTTP error statuses (404, 500). Always check response.ok or response.status. Pattern: const response = await fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token' }, body: JSON.stringify(data) }); if (!response.ok) throw new Error(`HTTP error: ${response.status}`); const json = await response.json();. Other body methods: response.text(), response.blob(), response.formData(). The Request object: new Request(url, options) — reusable request object. In LWC, Salesforce's locker service restricts direct fetch calls to same-origin or approved endpoints — use Named Credentials and Apex for cross-origin callouts.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.