Common Error Codes Every Programmer Should Know
Learn the most frequent error codes you'll encounter in programming, from HTTP status codes to compiler and runtime errors, with practical examples and how to fix them.
// table of contents (19 sections)
Errors are part of every programmer’s daily life. You can’t avoid them, but you can understand them quickly and fix them faster.
This guide covers the most common error codes you’ll encounter across different areas of programming, what they mean, and how to handle them.
HTTP Status Codes
When your app talks to servers or APIs, you’ll see these codes constantly.
Client Errors (4xx)
These mean the client did something wrong:
| Code | Name | What It Means | Common Cause |
|---|---|---|---|
| 400 | Bad Request | Invalid syntax or parameters | Missing required field, wrong data format |
| 401 | Unauthorized | Authentication required | No token, expired token, wrong credentials |
| 403 | Forbidden | You’re authenticated but not allowed | Insufficient permissions, IP blocked |
| 404 | Not Found | Resource doesn’t exist | Wrong URL, deleted resource, typo in endpoint |
| 405 | Method Not Allowed | Wrong HTTP method | POST to a GET-only endpoint |
| 408 | Request Timeout | Server got tired of waiting | Slow network, huge payload |
| 429 | Too Many Requests | You’re hitting the API too hard | Missing rate limiting, infinite loop in code |
Server Errors (5xx)
These mean the server messed up:
| Code | Name | What It Means | What to Do |
|---|---|---|---|
| 500 | Internal Server Error | Generic server failure | Check server logs, report to backend team |
| 502 | Bad Gateway | Server got invalid response | Server overload, upstream service down |
| 503 | Service Unavailable | Server can’t handle the request | Server maintenance, too many connections |
| 504 | Gateway Timeout | Upstream server too slow | Backend service hanging, network issues |
Handling HTTP Errors in Code
Future<User> fetchUser(int id) async {
final response = await http.get(Uri.parse('https://api.example.com/users/$id'));
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else if (response.statusCode == 404) {
throw UserNotFoundException('User $id does not exist');
} else if (response.statusCode == 401) {
throw AuthenticationException('Please log in again');
} else if (response.statusCode >= 500) {
throw ServerException('Server error. Try again later.');
} else {
throw ApiException('Failed to fetch user: ${response.statusCode}');
}
}
Pro tip: Always handle 4xx and 5xx differently. 4xx means your code needs fixing, 5xx means the server needs attention.
Compiler Errors
These appear when your code violates language syntax rules. The code won’t even run until you fix them.
Common Compiler Errors
1. Syntax Error
// Error: Expected ';' after this
var name = "Fira"
print(name)
Fix: Add the missing syntax.
var name = "Fira";
print(name);
2. Type Mismatch
// Error: A value of type 'String' can't be assigned to a variable of type 'int'
int age = "25";
Fix: Convert the type or use the correct type.
int age = 25;
// or
int age = int.parse("25");
3. Undefined Variable
// Error: Undefined name 'username'
print(username);
Fix: Declare the variable first.
String username = "abduarrahman";
print(username);
4. Missing Return Statement
// Error: A non-void function must return a value
int calculateSum(int a, int b) {
var result = a + b;
// Forgot to return!
}
Fix: Add the return statement.
int calculateSum(int a, int b) {
return a + b;
}
Runtime Errors
These happen while your code is running. The code compiles fine, but crashes during execution.
Common Runtime Errors
1. Null Pointer Exception
The most common error across all languages. You tried to use something that’s null or None.
String? name;
print(name.length); // Error: Null check operator used on a null value
Fix: Check for null before using.
String? name;
if (name != null) {
print(name.length);
}
// or
print(name?.length); // Safe navigation
2. Index Out of Bounds
You tried to access an array element that doesn’t exist.
var fruits = ['Apple', 'Banana'];
print(fruits[5]); // Error: RangeError (index): Invalid value: 5
Fix: Check the index against array length.
var fruits = ['Apple', 'Banana'];
if (5 < fruits.length) {
print(fruits[5]);
} else {
print('Index out of range');
}
3. Division by Zero
var result = 10 / 0; // Error: IntegerDivisionByZeroException
Fix: Check the divisor.
int divide(int a, int b) {
if (b == 0) {
throw ArgumentError('Cannot divide by zero');
}
return a ~/ b;
}
4. Stack Overflow
Usually caused by infinite recursion — a function that calls itself forever.
int countdown(int n) {
return countdown(n - 1); // No base case!
}
Fix: Always have a termination condition.
int countdown(int n) {
if (n <= 0) return 0; // Base case
return countdown(n - 1);
}
Database Errors
When working with databases, you’ll encounter these frequently:
| Error Code | Database | Meaning | Solution |
|---|---|---|---|
| 1062 | MySQL | Duplicate entry | Check for existing record before insert |
| 1215 | MySQL | Foreign key constraint fails | Ensure referenced record exists |
| 23505 | PostgreSQL | Unique violation | Similar to MySQL 1062 |
| 23503 | PostgreSQL | Foreign key violation | Similar to MySQL 1215 |
| SQLITE_CONSTRAINT | SQLite | Constraint violation | Check all constraints (unique, foreign key, not null) |
Example: Handling Database Errors
Future<void> insertUser(User user) async {
try {
await db.insert('users', user.toMap());
} on DatabaseException catch (e) {
if (e.toString().contains('UNIQUE constraint failed')) {
throw DuplicateEmailException('Email already registered');
} else if (e.toString().contains('FOREIGN KEY constraint failed')) {
throw InvalidReferenceException('Referenced record not found');
}
rethrow;
}
}
How to Read Error Messages
Error messages are clues, not insults. Here’s how to decode them:
Error: The method 'lenght' isn't defined for the class 'String'.
at main.dart:5:12
- What: The method
lenghtdoesn’t exist - Where:
main.dart, line 5, column 12 - Why: Typo! Should be
lengthnotlenght
The Error Message Anatomy
Error Type: What went wrong
at file:line:column
in function_name()
Caused by: More specific reason
Strategy:
- Read the error type first
- Go to the line number mentioned
- Look at nearby code (sometimes the error is on the line before)
- Read the stack trace from top to bottom — the top is where it crashed
Quick Debugging Checklist
When you encounter an error, go through this mental checklist:
□ Read the error message completely
□ Check the line number and file
□ Check for typos in variable/function names
□ Check for missing semicolons, brackets, parentheses
□ Check for null values before accessing properties
□ Check array bounds before accessing indices
□ Check function parameters and return types
□ Google the exact error message
□ Check if you modified the right file (you'd be surprised)
Best Practices for Error Handling
1. Fail Fast, Fail Clearly
Don’t let errors propagate silently. Catch them early and show meaningful messages.
// Bad
try {
// lots of code
} catch (e) {
print('Something went wrong'); // Useless
}
// Good
try {
await processPayment(amount);
} on InsufficientFundsException catch (e) {
throw PaymentException('Insufficient funds: ${e.message}');
} on NetworkException catch (e) {
throw PaymentException('Network error. Please try again.');
}
2. Use Custom Exception Classes
class AppException implements Exception {
final String message;
AppException(this.message);
@override
String toString() => message;
}
class NetworkException extends AppException {
NetworkException(String message) : super(message);
}
class ValidationException extends AppException {
ValidationException(String message) : super(message);
}
3. Log Errors for Debugging
try {
await riskyOperation();
} catch (e, stackTrace) {
logger.error('Operation failed', error: e, stackTrace: stackTrace);
rethrow;
}
Quick Reference Table
| Category | Common Errors | First Thing to Check |
|---|---|---|
| HTTP | 400, 401, 403, 404, 500 | Request parameters, auth token, URL |
| Compiler | Syntax, Type, Undefined | Typos, missing syntax, declarations |
| Runtime | Null, Index, Division | Null checks, array length, zero divisor |
| Database | Constraint, Duplicate | Data integrity, existing records |
What’s Next?
Now that you understand error codes, learn about proper error handling patterns to make your code more resilient and user-friendly.
Every error is a learning opportunity. The more you see them, the faster you’ll fix them. Keep coding! 🚀
You might also like
Think Like a Programmer: Mastering Basic Logic and Programming
Build a strong programming foundation by learning computational thinking, problem decomposition, flowcharts, pseudocode, and core logic concepts every developer needs.
Observability and Distributed Tracing: A Practical Guide for 2026
Master observability with distributed tracing, metrics, and logs. Learn OpenTelemetry setup, trace visualization, and production debugging with practical code examples.
AI Coding Assistants for Students: Free & Paid Guide 2026
Complete guide to free and paid AI coding tools for students — Cursor, Google Antigravity, Claude, Gemini, and GitHub Copilot with chat, web, and terminal access.
More Posts
API Gateway Patterns: The Front Door to Your Microservices
Web Components 2026: Building Framework-Agnostic UI Libraries
Building Autonomous AI Workflows with LangGraph: A Practical Guide
Building Type-Safe APIs with tRPC in 2026: Full-Stack TypeScript Without Schemas
Database Connection Pooling: Patterns for High-Performance Applications
Prompt Caching: Reduce LLM Costs by 90% with Smart Context Management
Enjoyed This Post?
Want to discuss the topic, have questions, or looking to collaborate on something similar? Drop a comment below or reach out directly.
