AJAX & Async Requests·AJAX from first request to live updates

Error handling

Separate network, HTTP, parse and application errors.

Beginner 13 min read Lesson 6 of 300 Challenge included
What you will be able to do
  • Use try/catch for network errors.
  • Check response.status for HTTP errors.
  • Wrap JSON parsing separately.
  • Show an actionable message.

In plain English

Different failures need different messages. A network error means connectivity; a 401 means sign in; a 422 means fix the form; a 500 means retry later. Do not show a generic "something went wrong" for all of them.

errors.jsJavaScript
try {
  const response = await fetch('/api/save', { method: 'POST', body })
  if (response.status === 401) return showSignIn()
  if (response.status === 422) return showFieldErrors(await response.json())
  if (!response.ok) throw new Error('Retry later')
} catch {
  showOfflineMessage()
}
Your turn

Handle a 422

Medium

Show field errors when the response status is 422.

JAVASCRIPT · starter
if (!response.ok)
Check your understanding before moving on.
Knowledge checkQuestion 1

Which status code usually means the user must sign in?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: CORS
Lesson 6 of 300 · 0% of course