Aller au contenu

Debugging Guide

This guide explains how to debug issues in the Plus261 project. Effective debugging requires understanding the tools and techniques available.

This guide will help you understand:

  • ✅ Available debugging tools and techniques
  • ✅ How to debug API and Web components
  • ✅ How to debug GraphQL queries and mutations
  • ✅ How to debug database issues
  • ✅ How to debug authentication and authorization
  • ✅ Common issues and solutions

Effective debugging requires understanding the tools and techniques available. This guide covers debugging for both API and Web components.

VS Code provides excellent debugging support for TypeScript.

  1. Create .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug API",
"type": "node",
"request": "launch",
"runtimeExecutable": "bun",
"runtimeArgs": ["--inspect", "dev"],
"cwd": "${workspaceFolder}/apps/api",
"console": "integratedTerminal"
},
{
"name": "Debug Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "bun",
"runtimeArgs": ["--inspect", "test"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal"
}
]
}
  1. Set breakpoints in your code
  2. Press F5 to start debugging

For debugging the web client:

Tool Purpose
Console JavaScript debugging
Network API requests inspection
React DevTools Component inspection
Performance Performance profiling

The GraphQL Playground is excellent for debugging API issues:

  • ✅ Test queries and mutations
  • ✅ Inspect errors
  • ✅ View request/response
  • ✅ Explore schema

Access: http://localhost:4000/graphql

Symptoms:

  • Requests timeout
  • 500 errors
  • No response

Debugging Steps:

Fenêtre de terminal
# 1. Check if API is running
curl http://localhost:4000/graphql
# 2. Check logs
tail -f apps/api/logs/app.log
# 3. Check database connection
kubectl -n plus261-app get pods
# 4. Check environment variables
cat apps/api/.env

Symptoms:

  • GraphQL errors in response
  • Field resolution errors
  • Type errors

Debugging Steps:

  1. Check Error Details in GraphQL Playground:
query {
products {
id
name
}
}
  1. Check Server Logs:
Fenêtre de terminal
# View API logs
tail -f apps/api/logs/app.log
  1. Add Logging:
@Query(() => [Product])
async products(@Ctx() context: Context) {
console.log('Query products', { userId: context.userId });
try {
return await this.service.query({ context, query: {} });
} catch (error) {
console.error('Error querying products', error);
throw error;
}
}

Symptoms:

  • Database connection errors
  • Query failures
  • Data not persisting

Debugging Steps:

  1. Check Database Connection:
Fenêtre de terminal
kubectl -n plus261-app get pods
kubectl -n plus261-app logs statefulset/postgres
  1. Use Drizzle Studio:
Fenêtre de terminal
bunx drizzle-kit studio
  1. Check Migrations:
Fenêtre de terminal
# List migrations
bunx drizzle-kit migrate
# Check migration status
bunx drizzle-kit check
  1. Test Query Directly:
import { db } from '../database';
const result = await db.select().from(users);
console.log('Users:', result);

Symptoms:

  • Unauthorized errors
  • Session expired
  • Permission denied

Debugging Steps:

  1. Check Session:
// In API code
console.log('Session:', context.session);
console.log('User:', context.user);
console.log('Permissions:', context.permissions);
  1. Test Authentication:
mutation {
signIn(email: "test@example.com", password: "password") {
token
user {
id
email
}
}
}

Symptoms:

  • Slow queries
  • High memory usage
  • Timeouts

Debugging Steps:

  1. Enable Query Logging:
// Log slow queries
const start = Date.now();
const result = await db.query(...);
const duration = Date.now() - start;
if (duration > 1000) {
console.warn('Slow query:', { duration, query });
}
  1. Use Performance Monitoring:
// Check metrics
import { getMetrics } from '../metrics/prometheus';
const metrics = getMetrics();
console.log('Metrics:', metrics);

Add strategic logging:

// Use appropriate log levels
logger.debug('Detailed debug info', { data });
logger.info('Informational message', { context });
logger.warn('Warning message', { issue });
logger.error('Error occurred', { error, context });

Set breakpoints in VS Code:

  1. Click in the gutter next to line number
  2. Run debugger (F5)
  3. Inspect variables
  4. Step through code (F10, F11)

For quick debugging:

console.log('Variable value:', variable);
console.table(arrayData);
console.dir(object, { depth: null });

Inspect errors thoroughly:

try {
// Code
} catch (error) {
console.error('Error details:', {
message: error.message,
stack: error.stack,
name: error.name,
cause: error.cause,
});
throw error;
}
  1. Use GraphQL Playground:
query {
products(filter: { status: { eq: "ACTIVE" } }) {
id
name
}
}
  1. Check Resolve Info:
@Query(() => [Product])
async products(
@Ctx() context: Context,
@GraphQLResultInfo() resolveInfo: GraphQLResolveInfoResult
) {
console.log('Requested fields:', resolveInfo.fields);
// ...
}
  1. Enable Query Logging:
// In database config
const db = drizzle(
postgres(connectionString, {
logger: true, // Log all queries
}),
);
  1. Use Drizzle Studio:
Fenêtre de terminal
bunx drizzle-kit studio
  1. Use Svelte DevTools:
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('Component mounted');
debugger; // Set breakpoint
});
</script>
  1. Inspect State:
<script>
let state = $state({ count: 0 });
$effect(() => {
console.log('State changed:', state);
});
</script>
  1. Check Network Tab in DevTools
  2. Inspect Requests:
// Log all requests
fetch('/graphql', {
method: 'POST',
body: JSON.stringify({ query }),
})
.then((response) => {
console.log('Response:', response);
return response.json();
})
.then((data) => {
console.log('Data:', data);
});
Issue Solution
Cannot find module rm -rf node_modules && bun install
Type errors bun --bun run check:code (root) or cd apps/web && bun --bun run check
Port already in use lsof -i :4000 && kill -9 <PID>
Database connection failed kubectl -n plus261-app get pods,svc and check Postgres readiness
  1. Add Logging Early - Don’t wait until you need to debug
  2. Use Appropriate Log Levels - debug, info, warn, error
  3. Include Context - User ID, request ID, etc.
  4. Test Locally First - Reproduce issues locally
  5. Use Debugger - Don’t just use console.log
  6. Document Issues - Keep notes on common problems
Tool Purpose Command/URL
VS Code Debugger Step-through debugging F5
GraphQL Playground Test queries http://localhost:4000/graphql
Drizzle Studio Database inspection bunx drizzle-kit studio
Browser DevTools Web debugging F12
Logs View application logs tail -f apps/api/logs/app.log

Continue learning:

  1. 🧪 Testing Guide - Testing strategies
  2. 🛠️ Development Workflow - Development process
  3. 📊 Observability - Monitoring and logging