Error Handling Patterns: Building Resilient Applications
January 25, 2024•1 min read
Error HandlingBest PracticesBackendReliability
# Error Handling Patterns: Building Resilient Applications
Effective error handling is crucial for building reliable applications. This guide covers error handling patterns and best practices.
## Error Types
### Custom Error Classes
```typescript
class AppError extends Error {
constructor(
public statusCode: number,
public message: string,
public isOperational = true
) {
super(message);
Error.captureStackTrace(this, this.constructor);
}
}
class NotFoundError extends AppError {
constructor(message = 'Resource not found') {
super(404, message);
}
}
```
### Error Handling Middleware
```typescript
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = exception instanceof HttpException
? exception.getStatus()
: 500;
response.status(status).json({
statusCode: status,
message: exception.message || 'Internal server error',
timestamp: new Date().toISOString(),
});
}
}
```
## Logging
```typescript
import { Logger } from '@nestjs/common';
@Injectable()
export class UserService {
private readonly logger = new Logger(UserService.name);
async createUser(data: CreateUserDto) {
try {
return await this.userRepository.create(data);
} catch (error) {
this.logger.error('Failed to create user', error.stack);
throw new AppError(500, 'Failed to create user');
}
}
}
```
## Conclusion
Proper error handling improves application reliability and user experience. Implement comprehensive error handling and logging.