HTTP

500 - Internal Server Error

Seeing a 500 Internal Server Error means the server crashed or encountered an unexpected condition—unhandled exceptions, database connection failures, memory exhaustion, or configuration mistakes. This server-side error (5xx) indicates the server failed, not your request. Most common when application code throws uncaught exceptions, but also appears when database connections fail, memory runs out, environment variables are missing, or server configuration is broken.

#Common Causes

  • Frontend: Client can't fix 500 errors directly, but rapid retries can worsen server load. Missing error boundaries in React apps crash the UI. No retry logic means users see cryptic errors.
  • Backend: Unhandled exceptions in application code (null pointer, undefined property access). Database connection pool exhausted or queries timeout. Memory leaks cause OOM (Out of Memory) errors. Missing environment variables or configuration files. Third-party API calls fail without error handling.
  • Infrastructure: Application server crashes (Node.js, Python, PHP). Database server is down or unreachable. Load balancer health checks fail. Container runs out of memory or CPU. File system permissions prevent writes.

Solutions

  1. 1Step 1: Diagnose - Check server logs immediately (tail -f /var/log/app/error.log or application logs). Look for stack traces, exception messages, or error codes. Check database connection status. Review memory/CPU usage (top, htop).
  2. 2Step 2: Diagnose - Check application monitoring (Sentry, DataDog, New Relic) for error details. Review database connection pool metrics. Check if specific endpoints trigger 500s. Examine recent deployments or configuration changes.
  3. 3Step 3: Fix - Client-side: Implement retry logic with exponential backoff for 500s. Show user-friendly error messages. Log 500 errors for monitoring. Implement circuit breakers to stop retrying failing endpoints.
  4. 4Step 4: Fix - Server-side: Add try-catch blocks around all async operations. Implement proper error handling middleware. Add database connection retry logic. Validate environment variables on startup. Add health check endpoints.
  5. 5Step 5: Fix - Infrastructure: Restart application server if it crashed. Check database server status and connectivity. Review load balancer health check configuration. Scale resources if memory/CPU exhausted. Fix file system permissions.

</>Code Examples

Fetch API: Retry Logic for 500 Errors
1// Client-side: Handle 500 errors with retry and user feedback
2async function fetchWithRetry(url, options = {}, maxRetries = 3) {
3  for (let attempt = 0; attempt < maxRetries; attempt++) {
4    try {
5      const response = await fetch(url, options);
6      
7      if (response.status === 500) {
8        if (attempt < maxRetries - 1) {
9          // Exponential backoff for server errors
10          const delay = Math.pow(2, attempt) * 1000;
11          console.warn(`Server error, retrying in ${delay}ms (attempt ${attempt + 1})`);
12          await new Promise(resolve => setTimeout(resolve, delay));
13          continue;
14        } else {
15          throw new Error('Server error after maximum retries');
16        }
17      }
18      
19      return response;
20} catch (error) {
21      if (attempt === maxRetries - 1) {
22        throw error;
23      }
24      // Network errors - retry with backoff
25      const delay = Math.pow(2, attempt) * 1000;
26      await new Promise(resolve => setTimeout(resolve, delay));
27    }
28  }
29}
30
31// Usage with user feedback
32async function loadData() {
33  try {
34    const response = await fetchWithRetry('/api/data');
35    return await response.json();
36  } catch (error) {
37    showUserMessage({
38      type: 'error',
39      title: 'Server Error',
40      message: 'The server encountered an error. Please try again in a moment.',
41    });
42    throw error;
43  }
44}
Express.js: Comprehensive Error Handling
1// Server-side: Proper error handling middleware
2const express = require('express');
3const app = express();
4
5// Async error wrapper
6const asyncHandler = (fn) => (req, res, next) => {
7  Promise.resolve(fn(req, res, next)).catch(next);
8};
9
10// Example route with error handling
11app.get('/api/users/:id', asyncHandler(async (req, res) => {
12  const userId = parseInt(req.params.id);
13  
14  if (isNaN(userId)) {
15    return res.status(400).json({ error: 'Invalid user ID' });
16  }
17  
18  // Database query with error handling
19  const user = await db.users.findById(userId);
20  
21  if (!user) {
22    return res.status(404).json({ error: 'User not found' });
23  }
24  
25  res.json(user);
26}));
27
28// Global error handling middleware (must be last)
29app.use((err, req, res, next) => {
30  console.error('Error:', err);
31  
32  // Log error to monitoring service (Sentry, etc.)
33  // logErrorToService(err, req);
34  
35  // Don't leak error details in production
36  const isDevelopment = process.env.NODE_ENV === 'development';
37  
38  res.status(err.status || 500).json({
39    error: 'Internal Server Error',
40    message: isDevelopment ? err.message : 'An unexpected error occurred',
41    ...(isDevelopment && { stack: err.stack }),
42  });
43});
44
45// Handle unhandled promise rejections
46process.on('unhandledRejection', (reason, promise) => {
47  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
48  // Log to error tracking service
49});
50
51// Handle uncaught exceptions
52process.on('uncaughtException', (error) => {
53  console.error('Uncaught Exception:', error);
54  // Log and exit gracefully
55  process.exit(1);
56});
Nginx: Error Handling and Logging
1# Nginx: Configure error handling and logging
2server {
3    listen 80;
4    server_name api.example.com;
5    
6    # Access and error logs
7    access_log /var/log/nginx/api_access.log;
8    error_log /var/log/nginx/api_error.log warn;
9    
10    location /api/ {
11        proxy_pass http://backend;
12        proxy_set_header Host $host;
13        proxy_set_header X-Real-IP $remote_addr;
14        
15        # Timeouts
16        proxy_connect_timeout 30s;
17        proxy_send_timeout 30s;
18        proxy_read_timeout 30s;
19        
20        # Error handling
21        proxy_intercept_errors on;
22        error_page 500 502 503 504 /50x.html;
23    }
24    
25    # Custom 500 error page
26    location = /50x.html {
27        root /usr/share/nginx/html;
28        internal;
29    }
30    
31    # Health check endpoint (bypasses error handling)
32    location /health {
33        proxy_pass http://backend/health;
34        access_log off;
35    }
36}

Related Errors

Provider Information

This error code is specific to HTTP services. For more information, refer to the official HTTP documentation.

500 - Internal Server Error | HTTP Error Reference | Error Code Reference