Glossary Term
HTTP Error Handling
Learn HTTP error handling best practices for detecting, managing, and responding to errors gracefully. Understand status codes, retry logic, and user feedback.
TL;DR: The practice of detecting and responding to HTTP failures gracefully instead of letting applications crash. Critical for building reliable user experiences.
HTTP error handling is the practice of properly detecting and responding to problems during HTTP communication. Instead of letting your application crash or confuse users, you gracefully manage failures with helpful feedback and recovery options.
Error Categories
4xx Client Errors: The request was invalid
400 Bad Request: Malformed request syntax401 Unauthorized: Authentication required403 Forbidden: Access denied404 Not Found: Resource doesn’t exist422 Unprocessable Entity: Valid syntax, invalid data
5xx Server Errors: The server failed to process a valid request
500 Internal Server Error: Generic server failure502 Bad Gateway: Upstream server error503 Service Unavailable: Server temporarily overloaded504 Gateway Timeout: Upstream server timeout
Best Practices
Provide Clear Feedback: Show users what went wrong and what they can do
if (response.status === 404) {
showMessage('Page not found. Check the URL or return to homepage.')
}
```javascript
**Implement Retry Logic**: Automatically retry transient failures
```javascript
const retryableErrors = [502, 503, 504]
if (retryableErrors.includes(response.status)) {
// Retry with exponential backoff
}
Log for Debugging: Record errors for developers while showing friendly messages to users
console.error(`API Error: ${response.status} - ${response.statusText}`)
showUserFriendlyMessage('Something went wrong. Please try again.')
User Experience Impact
Good error handling transforms frustrating failures into manageable situations:
- 404 errors: Show helpful navigation instead of blank pages
- 401 errors: Redirect to login while preserving the original destination
- 500 errors: Display maintenance messages with estimated recovery times
- Network errors: Offer offline functionality or retry options
Related: Status Code • Response • Request
Frequently Asked Questions
How should APIs handle errors?
Use appropriate status codes (4xx for client errors, 5xx for server errors), include error details in the response body, and be consistent across endpoints.
What should an error response include?
Include error code, human-readable message, and optionally details like field-specific errors. Use consistent JSON structure across all error responses.
Should I use 200 with error in body?
No, this is an anti-pattern. Use proper status codes so clients can handle errors correctly. 200 should only indicate success.
How do I handle errors in fetch?
Check response.ok or response.status. Fetch only rejects on network errors, not HTTP errors. You must check status codes manually.