Skip to content
· 8 min read · 0 views

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:

CodeNameWhat It MeansCommon Cause
400Bad RequestInvalid syntax or parametersMissing required field, wrong data format
401UnauthorizedAuthentication requiredNo token, expired token, wrong credentials
403ForbiddenYou’re authenticated but not allowedInsufficient permissions, IP blocked
404Not FoundResource doesn’t existWrong URL, deleted resource, typo in endpoint
405Method Not AllowedWrong HTTP methodPOST to a GET-only endpoint
408Request TimeoutServer got tired of waitingSlow network, huge payload
429Too Many RequestsYou’re hitting the API too hardMissing rate limiting, infinite loop in code

Server Errors (5xx)

These mean the server messed up:

CodeNameWhat It MeansWhat to Do
500Internal Server ErrorGeneric server failureCheck server logs, report to backend team
502Bad GatewayServer got invalid responseServer overload, upstream service down
503Service UnavailableServer can’t handle the requestServer maintenance, too many connections
504Gateway TimeoutUpstream server too slowBackend 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 CodeDatabaseMeaningSolution
1062MySQLDuplicate entryCheck for existing record before insert
1215MySQLForeign key constraint failsEnsure referenced record exists
23505PostgreSQLUnique violationSimilar to MySQL 1062
23503PostgreSQLForeign key violationSimilar to MySQL 1215
SQLITE_CONSTRAINTSQLiteConstraint violationCheck 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
  1. What: The method lenght doesn’t exist
  2. Where: main.dart, line 5, column 12
  3. Why: Typo! Should be length not lenght

The Error Message Anatomy

Error Type: What went wrong
  at file:line:column
  in function_name()
Caused by: More specific reason

Strategy:

  1. Read the error type first
  2. Go to the line number mentioned
  3. Look at nearby code (sometimes the error is on the line before)
  4. 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

CategoryCommon ErrorsFirst Thing to Check
HTTP400, 401, 403, 404, 500Request parameters, auth token, URL
CompilerSyntax, Type, UndefinedTypos, missing syntax, declarations
RuntimeNull, Index, DivisionNull checks, array length, zero divisor
DatabaseConstraint, DuplicateData 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

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.

Discussion