Skip to content

Fehler-Referenz

Audience: Dev, Ops
You will learn: - Vollständiger Katalog aller System-Fehler und deren Ursachen - Symptome, Diagnose und Lösungsschritte - Error-Codes und strukturierte Fehlermeldungen - Präventive Maßnahmen und Monitoring

Pre-requisites: - Troubleshooting Guide verstanden - System-Administration Kenntnisse - Zugriff auf Logs und Monitoring-Tools

Error-Code-Schema

Code-Format

{COMPONENT}-{CATEGORY}-{NUMBER}

Komponenten: - APP - Application-Level Fehler - API - API-spezifische Fehler
- ICO - Icon-Processing Fehler - FS - File-System Fehler - CFG - Configuration Fehler

Kategorien: - INIT - Initialization/Startup - PROC - Processing/Runtime - AUTH - Authentication/Authorization - VALID - Validation - NET - Network/Connectivity

Evidenz: Error handling patterns from application code

Application-Level Fehler (APP)

APP-INIT-001: Flask Application Start Failed

Beschreibung: Flask-Anwendung kann nicht gestartet werden

Symptome:

$ python app.py
Traceback (most recent call last):
  File "app.py", line 1, in <module>
    from flask import Flask
ModuleNotFoundError: No module named 'flask'

Diagnose:

# Python Environment prüfen
which python
python --version

# Dependencies prüfen
pip list | grep -i flask
pip show flask

Root Causes: 1. Missing Dependencies - Flask nicht installiert 2. Wrong Python Environment - Falsches Virtual Environment aktiv 3. Import Path Issues - Falsche PYTHONPATH-Konfiguration

Lösungen:

# 1. Dependencies installieren
pip install flask

# 2. Virtual Environment aktivieren
source venv/bin/activate
pip install flask

# 3. Python Path korrigieren
export PYTHONPATH=/opt/icon-tool:$PYTHONPATH

Prävention: - Requirements.txt verwenden - Virtual Environment dokumentieren - Health Checks vor Deployment

Evidenz: pyproject.toml:6-8, common startup issues

APP-INIT-002: Port Already in Use

Beschreibung: Ziel-Port ist bereits belegt

Symptome:

OSError: [Errno 98] Address already in use: ('0.0.0.0', 5000)

Diagnose:

# Port-Nutzung prüfen
lsof -i :5000
netstat -tulpn | grep :5000

# Prozess identifizieren
ps aux | grep python

Root Causes: 1. Previous Instance Running - Alte Instanz läuft noch 2. Port Conflict - Anderer Service nutzt Port 5000 3. Zombie Process - Prozess nicht ordnungsgemäß beendet

Lösungen:

# 1. Prozess beenden
sudo kill $(lsof -t -i:5000)

# 2. Alternativen Port verwenden
export PORT=5001
python app.py

# 3. Systemd Service proper restart
sudo systemctl stop icon-tool
sudo systemctl start icon-tool

Prävention: - Proper Service-Management (systemd) - Graceful Shutdown-Handler - Health Checks vor Start

APP-PROC-001: Memory Limit Exceeded

Beschreibung: Anwendung überschreitet Memory-Limits

Symptome:

MemoryError: Unable to allocate array
systemd[1]: icon-tool.service: A process of this unit has been killed by the OOM killer.

Diagnose:

# Memory-Verbrauch prüfen
ps aux | grep "python app.py" | awk '{print $6/1024 " MB"}'

# System Memory
free -h
cat /proc/meminfo | grep Available

# Memory Limits
systemctl show icon-tool --property=MemoryLimit

Root Causes: 1. Memory Leak - Graduelle Memory-Akkumulation 2. Large Dataset - Zu viele Icons in Memory 3. Inefficient Caching - Cache-Größe nicht begrenzt

Lösungen:

# 1. Memory Limit erhöhen (temporär)
sudo systemctl edit icon-tool
# [Service]
# MemoryLimit=200M

# 2. Cache optimieren
export CACHE_TIMEOUT=60  # Shorter cache time
export MAX_ICONS=500     # Limit icon count

# 3. Application restart
sudo systemctl restart icon-tool

Prävention: - Memory-Monitoring implementieren - Garbage Collection optimieren - Icon-Anzahl begrenzen

Evidenz: Resource management needs, performance constraints

API-Level Fehler (API)

API-PROC-001: Icon Not Found

HTTP Status: 404
Error Code: API-PROC-001

Beschreibung: Angefragtes Icon existiert nicht

Symptome:

{
  "error": "Icon not found",
  "code": "API-PROC-001",
  "details": {
    "requested_icon": "nonexistent",
    "available_icons": 162
  }
}

Diagnose:

# Icon existence check
ls static/icons/ | grep "nonexistent.svg"

# API response debug
curl -v http://localhost:5000/api/icon/nonexistent

Root Causes: 1. Typo in Icon Name - Falsche Schreibweise 2. Icon Not Extracted - Icon nicht in SVG-Sammlung 3. Metadata Mismatch - Icon in Metadaten aber nicht als Datei

Lösungen:

# 1. Verfügbare Icons auflisten
curl -s http://localhost:5000/api/icons | jq '.icons[].name'

# 2. Icons neu extrahieren
node extract-icons.js

# 3. Metadaten-Konsistenz prüfen
python -c "
import json, os
with open('icons.json') as f: cats = json.load(f)
actual = set(os.listdir('static/icons'))
categorized = set(sum(cats.values(), []))
print('Missing:', categorized - actual)
"

Prävention: - Icon-Name-Validation - Automated testing - Consistency checks

API-PROC-002: Invalid JSON Response

HTTP Status: 500
Error Code: API-PROC-002

Beschreibung: API kann keine gültige JSON-Response generieren

Symptome:

curl http://localhost:5000/api/icons
# Returns HTML error page instead of JSON

Diagnose:

# Check metadata file
python -c "import json; json.load(open('icons.json'))"

# Check Flask error logs
tail -50 logs/icon-tool.log | grep ERROR

Root Causes: 1. Corrupted Metadata - icons.json invalid 2. Unicode Issues - Encoding-Probleme 3. Circular References - JSON-Serialisierung fehlgeschlagen

Lösungen:

# 1. Metadata reparieren
cp icons.json icons.json.backup
python -c "
import json
try:
    with open('icons.json') as f: data = json.load(f)
    print('JSON is valid')
except Exception as e:
    print('JSON error:', e)
    # Create minimal valid structure
    with open('icons.json', 'w') as f:
        json.dump({'Uncategorized': []}, f)
"

# 2. Service restart
systemctl restart icon-tool

Evidenz: app.py:51-55 JSON response handling

Icon-Processing Fehler (ICO)

ICO-PROC-001: FontAwesome Icon Not Found

Beschreibung: Icon-Name existiert nicht in FontAwesome-Bibliothek

Symptome:

$ node extract-icons.js
 faInvalidIcon nicht gefunden
 161 Icons erfolgreich extrahiert (1 failed)

Diagnose:

# FontAwesome-Icons auflisten
node -e "
const icons = require('@fortawesome/free-solid-svg-icons');
console.log(Object.keys(icons).filter(k => k.startsWith('fa')));
"

# Specific Icon check
node -e "
const { faInvalidIcon } = require('@fortawesome/free-solid-svg-icons');
console.log(faInvalidIcon || 'Icon not found');
"

Root Causes: 1. Typo in Icon Name - Falsche FontAwesome-Benennung 2. Wrong Icon Set - Icon nicht in Free Solid Set 3. Version Mismatch - Icon in anderer FontAwesome-Version

Lösungen:

# 1. Korrekte Icon-Namen recherchieren
# https://fontawesome.com/icons?s=solid&f=free

# 2. extract-icons.js korrigieren
# Remove invalid icon from icons object

# 3. FontAwesome Version prüfen
npm list @fortawesome/free-solid-svg-icons

Prävention: - Icon-Name-Validation vor Hinzufügung - FontAwesome-Dokumentation konsultieren - Version-Pinning in package.json

Evidenz: extract-icons.js:9-270, FontAwesome integration

ICO-PROC-002: SVG Generation Failed

Beschreibung: SVG-Generierung aus FontAwesome-Icon fehlgeschlagen

Symptome:

$ node extract-icons.js
 faHome  processing...
 Error generating SVG for faHome: Invalid icon definition

Diagnose:

# Manual SVG generation test
node -e "
const { icon } = require('@fortawesome/fontawesome-svg-core');
const { faHome } = require('@fortawesome/free-solid-svg-icons');
try {
  const svgIcon = icon(faHome);
  console.log('SVG generated successfully');
  console.log(svgIcon.html[0]);
} catch (e) {
  console.error('SVG generation failed:', e);
}
"

Root Causes: 1. Corrupted Icon Definition - FontAwesome-Daten beschädigt 2. Library Version Conflict - Inkompatible Versionen 3. Memory Issues - Nicht genug Memory für SVG-Generierung

Lösungen:

# 1. Dependencies neu installieren
rm -rf node_modules package-lock.json
npm install

# 2. Memory für Node.js erhöhen
export NODE_OPTIONS="--max-old-space-size=1024"
node extract-icons.js

# 3. FontAwesome-Cache leeren
npm cache clean --force

ICO-FS-001: Unable to Write SVG File

Beschreibung: SVG-Datei kann nicht geschrieben werden

Symptome:

$ node extract-icons.js
 faHome  SVG generated
 Error writing static/icons/home.svg: EACCES: permission denied

Diagnose:

# Directory permissions
ls -ld static/icons/
ls -la static/icons/ | head -5

# Disk space
df -h .

# Write permissions test
touch static/icons/test.svg && rm static/icons/test.svg

Root Causes: 1. Permission Denied - Keine Schreibrechte auf Directory 2. Disk Full - Kein Speicherplatz verfügbar 3. Directory Missing - static/icons/ existiert nicht

Lösungen:

# 1. Permissions korrigieren
sudo chown -R $(whoami):$(whoami) static/icons/
chmod 755 static/icons/
chmod 644 static/icons/*.svg

# 2. Directory erstellen
mkdir -p static/icons

# 3. Disk space freigeben
df -h
du -sh static/icons/
# Clean up old files if needed

Evidenz: File system operations, permission management

File-System Fehler (FS)

FS-PROC-001: Metadata File Corrupted

Beschreibung: icons.json ist beschädigt oder nicht lesbar

Symptome:

json.decoder.JSONDecodeError: Expecting ',' delimiter: line 15 column 5 (char 234)

Diagnose:

# JSON-Syntax prüfen
python -c "import json; json.load(open('icons.json'))"

# File integrity
file icons.json
wc -l icons.json

Root Causes: 1. Manual Edit Error - Manuelle Bearbeitung mit Syntax-Fehler 2. Incomplete Write - Datei-Schreibvorgang unterbrochen 3. Encoding Issues - Falsche Zeichenkodierung

Lösungen:

# 1. Backup wiederherstellen
cp icons.json.backup icons.json

# 2. Minimal JSON erstellen
echo '{"Uncategorized": []}' > icons.json

# 3. Automatische Reparatur
python -c "
import json, os
# Get all SVG files
icons = [f for f in os.listdir('static/icons') if f.endswith('.svg')]
# Create basic categorization
categories = {'All Icons': sorted(icons)}
with open('icons.json', 'w') as f:
    json.dump(categories, f, indent=2)
print(f'Created metadata for {len(icons)} icons')
"

FS-PROC-002: Icons Directory Missing

Beschreibung: static/icons/ Directory existiert nicht

Symptome:

FileNotFoundError: [Errno 2] No such file or directory: 'static/icons'

Diagnose:

# Directory structure
ls -la static/
find . -name "icons" -type d

# Application working directory
pwd
echo $PWD

Root Causes: 1. Working Directory - Falsches Working Directory 2. Deployment Issue - Directory bei Deployment nicht erstellt 3. Permissions - Directory wurde gelöscht/umbenannt

Lösungen:

# 1. Directory erstellen
mkdir -p static/icons

# 2. Icons extrahieren
node extract-icons.js

# 3. Permissions setzen
chmod 755 static/icons/

Evidenz: Directory structure requirements, deployment patterns

Configuration Fehler (CFG)

CFG-VALID-001: Invalid Environment Variable

Beschreibung: Environment-Variable hat ungültigen Wert

Symptome:

ValueError: invalid literal for int() with base 10: 'invalid'

Diagnose:

# Environment variables checken
env | grep -E '^(FLASK|ICON|MAX|PORT)_'

# Specific variable validation
python -c "
import os
try:
    max_icons = int(os.environ.get('MAX_ICONS', '1000'))
    print(f'MAX_ICONS: {max_icons}')
except ValueError as e:
    print(f'Invalid MAX_ICONS: {e}')
"

Root Causes: 1. Type Mismatch - String statt Number 2. Invalid Range - Wert außerhalb gültigen Bereichs 3. Missing Variable - Required Variable nicht gesetzt

Lösungen:

# 1. Korrekte Werte setzen
export MAX_ICONS=1000
export PORT=5000
export FLASK_DEBUG=true  # not True

# 2. Configuration validation
python -c "
from config import ConfigValidator
errors = ConfigValidator.validate_config()
if errors:
    for error in errors: print(f'Error: {error}')
else:
    print('Configuration valid')
"

CFG-VALID-002: Missing Required Configuration

Beschreibung: Erforderliche Konfiguration fehlt

Symptome:

RuntimeError: SECRET_KEY is required in production

Diagnose:

# Required variables check
echo "SECRET_KEY: ${SECRET_KEY:-NOT SET}"
echo "FLASK_ENV: ${FLASK_ENV:-NOT SET}"

# Configuration completeness
python -c "
import os
required = ['SECRET_KEY', 'FLASK_ENV']
missing = [var for var in required if not os.environ.get(var)]
if missing:
    print(f'Missing: {missing}')
else:
    print('All required variables set')
"

Root Causes: 1. Missing .env File - Environment-Datei nicht geladen 2. Production Setup - Production-spezifische Variablen fehlen 3. Service Configuration - systemd-Service ohne Environment

Lösungen:

# 1. Environment file erstellen
cat > .env << EOF
SECRET_KEY=$(openssl rand -hex 32)
FLASK_ENV=production
FLASK_DEBUG=false
EOF

# 2. Environment laden
source .env

# 3. systemd Service konfigurieren
sudo systemctl edit icon-tool
# [Service]
# Environment=SECRET_KEY=your-secret-here

Evidenz: Configuration requirements, security needs

Monitoring & Alerting

Error-Rate-Monitoring

#!/bin/bash
# scripts/error-monitoring.sh

LOG_FILE="/opt/icon-tool/logs/icon-tool.log"
TIME_WINDOW="5 minutes"

# Count errors in time window
error_count=$(grep -c "ERROR" <(tail -n 1000 "$LOG_FILE"))
total_requests=$(grep -c "Request:" <(tail -n 1000 "$LOG_FILE"))

if [ $total_requests -gt 0 ]; then
    error_rate=$(echo "scale=2; $error_count / $total_requests * 100" | bc)
    echo "Error rate: $error_rate% ($error_count/$total_requests)"

    # Alert threshold: 5%
    if (( $(echo "$error_rate > 5" | bc -l) )); then
        echo "⚠️  High error rate detected: $error_rate%"
        # Send alert (email, Slack, etc.)
    fi
else
    echo "No requests found in log"
fi

Error-Pattern-Detection

# Pattern detection for common errors
grep -E "(Memory|Permission|Connection)" "$LOG_FILE" | tail -10

# Correlation analysis
python3 -c "
import re
from collections import Counter

with open('$LOG_FILE') as f:
    lines = f.readlines()

# Extract error patterns
errors = []
for line in lines:
    if 'ERROR' in line:
        # Extract error type
        if 'FileNotFoundError' in line:
            errors.append('FILE_NOT_FOUND')
        elif 'PermissionError' in line:
            errors.append('PERMISSION_DENIED')
        elif 'MemoryError' in line:
            errors.append('MEMORY_ERROR')
        elif 'ConnectionError' in line:
            errors.append('CONNECTION_ERROR')

# Count error types
counter = Counter(errors)
for error, count in counter.most_common():
    print(f'{error}: {count}')
"

Automated Error Resolution

# auto_recovery.py
import subprocess
import time
import requests

class AutoRecovery:
    def __init__(self):
        self.recovery_actions = {
            'SERVICE_DOWN': self.restart_service,
            'MEMORY_ERROR': self.restart_with_limits,
            'PERMISSION_ERROR': self.fix_permissions,
            'FILE_NOT_FOUND': self.restore_files
        }

    def detect_issue(self):
        """Detect current system issues"""
        try:
            response = requests.get('http://localhost:5000/health', timeout=5)
            if response.status_code != 200:
                return 'SERVICE_DOWN'
        except requests.ConnectionError:
            return 'SERVICE_DOWN'

        # Check memory usage
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        for line in result.stdout.split('\n'):
            if 'python app.py' in line:
                memory_mb = int(line.split()[5]) / 1024
                if memory_mb > 150:  # 150MB threshold
                    return 'MEMORY_ERROR'

        return None

    def restart_service(self):
        """Restart the icon-tool service"""
        subprocess.run(['sudo', 'systemctl', 'restart', 'icon-tool'])
        time.sleep(10)
        return self.verify_recovery()

    def restart_with_limits(self):
        """Restart with memory limits"""
        subprocess.run(['sudo', 'systemctl', 'stop', 'icon-tool'])
        subprocess.run(['sudo', 'systemctl', 'set-property', 'icon-tool', 'MemoryLimit=100M'])
        subprocess.run(['sudo', 'systemctl', 'start', 'icon-tool'])
        time.sleep(10)
        return self.verify_recovery()

    def fix_permissions(self):
        """Fix file permissions"""
        subprocess.run(['sudo', 'chown', '-R', 'iconuser:icongroup', '/opt/icon-tool/'])
        subprocess.run(['sudo', 'chmod', '755', '/opt/icon-tool/static/icons/'])
        return True

    def restore_files(self):
        """Restore missing files"""
        subprocess.run(['node', '/opt/icon-tool/extract-icons.js'])
        return True

    def verify_recovery(self):
        """Verify system is healthy after recovery"""
        try:
            response = requests.get('http://localhost:5000/health', timeout=10)
            return response.status_code == 200
        except:
            return False

# Usage
if __name__ == '__main__':
    recovery = AutoRecovery()
    issue = recovery.detect_issue()

    if issue:
        print(f"Detected issue: {issue}")
        if issue in recovery.recovery_actions:
            success = recovery.recovery_actions[issue]()
            print(f"Recovery {'successful' if success else 'failed'}")
        else:
            print("No automated recovery available")
    else:
        print("System healthy")

Evidenz: Error monitoring patterns, automated recovery strategies


Error-Management-Checkliste: - [ ] Error-Codes dokumentiert und implementiert - [ ] Strukturierte Error-Responses in API - [ ] Monitoring für Error-Rates aktiviert - [ ] Automated Recovery für häufige Probleme - [ ] Escalation-Pfade für kritische Fehler definiert - [ ] Error-Pattern-Detection implementiert