Error Formatting
Logluxe provides utilities to make errors more readable and debugging easier.
Basic Error Logging
log.error(error)
Automatically format Error objects:
import { log } from 'logluxe';
try {
throw new Error('Something went wrong');
} catch (error) {
log.error(error);
}
Error Output
✖✖ Error: Something went wrong
● at functionName (file.js:10:5)
● at anotherFunction (file.js:20:3)
🎮 Try Error Logging
Pretty Stack Traces
log.stack(error)
Format stack traces with syntax highlighting:
try {
riskyOperation();
} catch (error) {
log.stack(error);
}
Pretty Stack Trace
✖Error: Connection refused
at connectDatabase (src/db/connection.ts:45:12)
at initializeApp (src/app.ts:23:5)
at main (src/index.ts:10:3)
Caused by: ECONNREFUSED 127.0.0.1:5432
Stack Trace Highlighting
The stack trace is formatted with:
- Error message in red
- File paths in cyan
- Line numbers in yellow
- Function names in white
- Node internals dimmed
Error Context
Adding Context to Errors
function fetchUser(id: string) {
try {
return database.findUser(id);
} catch (error) {
log.error(`Failed to fetch user ${id}`);
log.stack(error);
throw error;
}
}
Error with Context
✖✖ Failed to fetch user abc123
✖Error: User not found
at Database.findUser (src/db.ts:45:12)
at fetchUser (src/users.ts:10:20)
Error with Additional Data
function processPayment(payment: Payment) {
try {
return gateway.charge(payment);
} catch (error) {
log.group('Payment Error');
log.error(error.message);
log.debug('Payment details:', {
amount: payment.amount,
currency: payment.currency,
method: payment.method
});
log.stack(error);
log.end();
throw error;
}
}
Payment Error with Details
┌ Payment Error
✖│ ✖ Card declined: insufficient funds
●│ ● Payment details: {
●│ amount: 99.99,
●│ currency: 'USD',
●│ method: 'credit_card'
●│ }
●│ at Gateway.charge (gateway.ts:123:8)
└
🎮 Try Error Grouping
Error Box
log.errorBox(error)
Display errors in a prominent box:
try {
criticalOperation();
} catch (error) {
log.errorBox(error);
}
Error Box
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ❌ ERROR ┃
┃ ┃
┃ Connection to database failed ┃
┃ ┃
┃ at connectDB (src/db.ts:23:5) ┃
┃ at init (src/app.ts:10:3) ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
Custom Error Types
Formatting Custom Errors
class ValidationError extends Error {
constructor(
message: string,
public field: string,
public value: unknown
) {
super(message);
this.name = 'ValidationError';
}
}
// Log custom error with context
try {
validateInput(data);
} catch (error) {
if (error instanceof ValidationError) {
log.error(`Validation failed for field "${error.field}"`);
log.debug(`Invalid value: ${error.value}`);
log.debug(`Error: ${error.message}`);
} else {
log.error(error);
}
}
Validation Error
✖✖ Validation failed for field "email"
●● Invalid value: "not-an-email"
●● Error: Invalid email format
Practical Examples
API Error Handler
function handleApiError(error: unknown, context: string) {
log.group(`API Error: ${context}`);
if (error instanceof Response) {
log.error(`HTTP ${error.status}: ${error.statusText}`);
log.debug(`URL: ${error.url}`);
} else if (error instanceof Error) {
log.error(error.message);
log.dev(error.stack);
} else {
log.error(String(error));
}
log.end();
}
API Error Handler
┌ API Error: Fetch users
✖│ ✖ HTTP 500: Internal Server Error
●│ ● URL: https://api.example.com/users
└
Database Error Handler
function handleDatabaseError(error: unknown, query?: string) {
log.group('Database Error');
if (query) {
log.debug('Query:', query);
}
if (error instanceof Error) {
// Detect specific database errors
if (error.message.includes('ECONNREFUSED')) {
log.error('Database connection refused');
log.warn('Is the database server running?');
} else if (error.message.includes('duplicate key')) {
log.error('Duplicate key violation');
} else if (error.message.includes('timeout')) {
log.error('Query timeout');
log.warn('Consider optimizing the query');
} else {
log.error(error.message);
}
log.dev(error.stack);
}
log.end();
}
Database Error Handler
┌ Database Error
●│ ● Query: SELECT * FROM users WHERE id = 'abc123'
✖│ ✖ Database connection refused
⚠│ ⚠ Is the database server running?
└
🎮 Try Database Error
Express Error Middleware
import { log } from 'logluxe';
function errorMiddleware(err: Error, req: Request, res: Response, next: Function) {
const requestId = req.headers['x-request-id'];
log.group(`Error [${requestId}]`);
log.error(`${req.method} ${req.path}`);
log.error(err.message);
// Show stack trace only in development
log.dev(err.stack);
// Log request details in development
log.dev('Request body:', req.body);
log.dev('Request query:', req.query);
log.end();
// Send error response
res.status(500).json({
error: process.env.NODE_ENV === 'production'
? 'Internal Server Error'
: err.message
});
}
Express Error Middleware
┌ Error [req_abc123]
✖│ ✖ POST /api/users
✖│ ✖ Validation failed: email is required
●│ ● Request body: { name: 'John' }
●│ ● Request query: {}
└
Validation Error Reporter
interface ValidationResult {
field: string;
message: string;
value?: unknown;
}
function reportValidationErrors(errors: ValidationResult[]) {
console.log('');
log.paint(' VALIDATION ERRORS ').white().bgRed().bold().print();
console.log('');
errors.forEach((error, index) => {
log.error(`${index + 1}. ${error.field}: ${error.message}`);
if (error.value !== undefined) {
log.debug(` Received: ${JSON.stringify(error.value)}`);
}
});
console.log('');
log.paint(`${errors.length} error(s) found`).red().dim().print();
console.log('');
}
Validation Error Report
VALIDATION ERRORS
✖✖ 1. email: Invalid email format
● Received: "not-an-email"
✖✖ 2. age: Must be a positive number
● Received: -5
✖✖ 3. name: Required field is missing
3 error(s) found
Best Practices
1. Always Provide Context
// Good: Context included
log.error(`Failed to process order ${orderId}`);
log.stack(error);
// Bad: No context
log.error(error);
2. Log at Appropriate Levels
// Critical: Use error box
if (error.critical) {
log.errorBox(error);
}
// Standard: Use log.error
log.error(error.message);
// Debug info: Use log.dev
log.dev(error.stack);
3. Include Recovery Information
log.error('Database connection failed');
log.warn('Retrying in 5 seconds...');
log.info('Check DATABASE_URL environment variable');
Error with Recovery Info
✖✖ Database connection failed
⚠⚠ Retrying in 5 seconds...
ℹℹ Check DATABASE_URL environment variable
4. Structured Errors in Production
if (env.isProd) {
console.log(JSON.stringify({
level: 'error',
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString(),
context: { userId, requestId }
}));
} else {
log.errorBox(error);
}
Next: Themes & Presets →