Troubleshooting
This guide helps you diagnose and resolve common issues when working with ziegel packages.
Common Issues
Installation Problems
Package Not Found
Error: npm ERR! 404 Not Found - GET https://registry.npmjs.org/@breadstone/ziegel-core
Solution: ziegel packages are published to a private Azure DevOps registry. Configure your npm to use the correct registry:
# Configure npm to use the Azure DevOps registry
npm config set registry https://breadstone.pkgs.visualstudio.com/ziegel/_packaging/breadstone-ziegel-public/npm/registry/
# Or use .npmrc file
echo "registry=https://breadstone.pkgs.visualstudio.com/ziegel/_packaging/breadstone-ziegel-public/npm/registry/" > .npmrcAuthentication Issues
Error: npm ERR! 401 Unauthorized
Solution: You need proper authentication credentials for the private registry. Contact your administrator for access.
TypeScript Compilation Issues
Type Definition Errors
Error: Cannot find module '@breadstone/ziegel-core' or its corresponding type declarations
Solution:
Ensure the package is properly installed:
bashnpm install @breadstone/ziegel-coreCheck your
tsconfig.jsonincludes the correct module resolution:json{ "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true } }Clear TypeScript cache:
bashrm -rf node_modules/.cache/typescript npx tsc --build --clean
Generic Type Issues
Error: Type 'unknown' is not assignable to type 'T'
Solution: Ensure proper type annotations when using generic methods:
// ❌ Incorrect
const config = ServiceLocator.get('config');
// ✅ Correct
const config = ServiceLocator.get<ConfigurationManager>('config');Runtime Issues
Service Not Registered
Error: Service not found: userService
Solution: Ensure services are registered before they're accessed:
// Register services at application startup
ServiceLocator.register('userService', () => new UserService());
// Then use the service
const userService = ServiceLocator.get<UserService>('userService');Circular Dependencies
Error: RangeError: Maximum call stack size exceeded
Solution: Restructure your dependencies to avoid circular references:
// ❌ Circular dependency
class UserService {
constructor(private orderService: OrderService) {}
}
class OrderService {
constructor(private userService: UserService) {} // Circular!
}
// ✅ Use events or interfaces to break the cycle
class UserService {
constructor(private eventAggregator: EventAggregator) {}
createUser(userData: any) {
const user = this.createUserRecord(userData);
this.eventAggregator.publish('user:created', user);
return user;
}
}
class OrderService {
constructor(private eventAggregator: EventAggregator) {
this.eventAggregator.subscribe('user:created', this.onUserCreated.bind(this));
}
onUserCreated(user: User) {
// Handle user creation
}
}HTTP Client Issues
CORS Errors
Error: Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy
Solution: This is a server-side configuration issue. Contact your API administrator to configure CORS headers, or use a proxy during development:
// Development proxy configuration
const httpClient = new HttpClient('/api', {
// Your local proxy will forward to the actual API
});Request Timeout
Error: Request timeout of 5000ms exceeded
Solution: Increase timeout or implement retry logic:
const httpClient = new HttpClient('https://api.example.com', {
timeout: 30000, // 30 seconds
retryAttempts: 3,
retryDelay: 1000
});Authentication Failures
Error: 401 Unauthorized
Solution: Ensure your authentication interceptor is properly configured:
class AuthInterceptor implements HttpInterceptor {
async intercept(request: Request): Promise<Request> {
const token = await this.getValidToken(); // Ensure token is valid
if (token) {
request.headers.set('Authorization', `Bearer ${token}`);
}
return request;
}
private async getValidToken(): Promise<string | null> {
let token = localStorage.getItem('authToken');
// Check if token needs refresh
if (this.isTokenExpired(token)) {
token = await this.refreshToken();
}
return token;
}
}Configuration Issues
Configuration Not Loading
Error: Configuration value not found: database:connectionString
Solution:
Verify configuration files exist and are properly formatted:
json// appsettings.json { "database": { "connectionString": "your-connection-string" } }Ensure configuration is loaded before accessing values:
typescriptconst config = new ConfigurationManager(); await config.addJsonFile('appsettings.json'); // Make sure this completes const connectionString = config.getValue<string>('database:connectionString');Check file paths are correct relative to your application root.
Environment Variables Not Working
Error: Environment variables are not being loaded
Solution: Ensure environment variables are properly configured:
// Load environment variables
const config = new ConfigurationManager();
config.addEnvironmentVariables('MYAPP_'); // Prefix optional
// Access with proper naming
const dbUrl = config.getValue<string>('database:url');
// Looks for MYAPP_DATABASE__URL (double underscore for hierarchy)Localization Issues
Missing Translations
Error: Translation keys return [key] instead of translated text
Solution:
Verify translation files are loaded:
typescriptconst translations = new Map([ ['en-US', new Map([ ['welcome', 'Welcome!'] ])] ]); const provider = new MapLocalizationProvider(translations);Check culture is set correctly:
typescriptawait localizationManager.setCulture('en-US');Implement proper fallback handling:
typescriptconst localizationManager = new LocalizationManager( provider, cultureProvider, (key, culture) => { console.warn(`Missing translation: ${key} for ${culture}`); return key; // Return key as fallback } );
Culture Changes Not Reflected
Error: UI doesn't update when culture changes
Solution: Subscribe to culture change events:
const cultureProvider = new CultureProvider();
cultureProvider.cultureChanged.add((newCulture) => {
// Reload UI components
this.updateUserInterface();
// Reload localized content
this.reloadLocalizedContent();
});Performance Issues
Slow Application Startup
Symptoms: Long delays during application initialization
Solution:
Use lazy loading for expensive services:
typescriptServiceLocator.register('expensiveService', () => { // Only create when first accessed return new ExpensiveService(); });Parallelize independent initialization tasks:
typescriptasync initialize() { await Promise.all([ this.initializeConfiguration(), this.initializeLogging(), this.initializeLocalization() ]); }
Large Bundle Size
Symptoms: Application bundle is larger than expected
Solution:
Use tree-shaking friendly imports:
typescript// ✅ Good - tree-shakeable import { StringExtensions } from '@breadstone/ziegel-core'; // ❌ Bad - imports entire package import * as ZiegelCore from '@breadstone/ziegel-core';Analyze your bundle to identify large dependencies:
bashnpm install --save-dev webpack-bundle-analyzer # Analyze your buildUse dynamic imports for optional features:
typescriptasync loadOptionalFeature() { if (featureEnabled) { const { OptionalService } = await import('./OptionalService'); return new OptionalService(); } }
Memory Leaks
Symptoms: Memory usage grows over time
Solution:
Properly dispose of event subscriptions:
typescriptclass UserService { private subscriptions: Array<() => void> = []; constructor(eventAggregator: EventAggregator) { const unsubscribe = eventAggregator.subscribe('event', this.handler); this.subscriptions.push(unsubscribe); } dispose() { this.subscriptions.forEach(unsub => unsub()); this.subscriptions = []; } }Clear caches when appropriate:
typescriptclass CacheManager { private cache = new Map(); clear() { this.cache.clear(); } // Clear cache periodically startCleanup() { setInterval(() => this.clear(), 60000); // Every minute } }
Debugging Tips
Enable Debug Logging
// Enable debug logging in development
if (process.env.NODE_ENV === 'development') {
LoggerManager.configure({
level: LogLevel.Debug,
providers: [new ConsoleLogProvider()]
});
}Use Browser DevTools
- Network Tab: Monitor HTTP requests and responses
- Console: Check for JavaScript errors and log messages
- Application Tab: Inspect localStorage, sessionStorage, and cookies
- Performance Tab: Profile application performance
TypeScript Debugging
// Add type assertions for debugging
function debugUser(user: unknown) {
console.log('User type check:', TypeGuard.isObject(user));
console.log('Has name property:', TypeGuard.hasProperty(user, 'name'));
if (TypeGuard.isObject(user) && TypeGuard.hasProperty(user, 'name')) {
console.log('User name:', user.name);
}
}Getting Help
Before Seeking Help
- Check this troubleshooting guide
- Review the relevant package documentation
- Check existing issues on Azure DevOps
- Ensure you're using the latest version
Creating Bug Reports
When reporting issues, include:
Environment information:
- Node.js version
- TypeScript version
- Package versions
- Operating system
Steps to reproduce:
1. Install packages 2. Create service with configuration X 3. Call method Y 4. Observe error ZExpected vs actual behavior
Minimal reproduction case
Error messages and stack traces
Support Channels
- Azure DevOps Issues: Create Bug Report
- Documentation: Package Guides
- Examples: Usage Examples
Quick Reference
Common Commands
# Clear npm cache
npm cache clean --force
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install
# Clear TypeScript cache
rm -rf node_modules/.cache/typescript
# Check package versions
npm list @breadstone/ziegel-core
# Build with verbose output
npm run build -- --verboseEnvironment Variables
# Common ziegel environment variables
NODE_ENV=development
ZIEGEL_LOG_LEVEL=debug
ZIEGEL_CONFIG_PATH=/path/to/configConfiguration Examples
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"skipLibCheck": true
}
}// package.json
{
"dependencies": {
"@breadstone/ziegel-core": "^0.0.1",
"@breadstone/ziegel-platform": "^0.0.1"
}
}