Обработка ошибок и логирование
Relevant source files
The following files were used as context for generating this wiki page:
This module provides a centralized system for managing application errors and logging telemetry within the music service. It ensures consistent HTTP responses, structured logging using the zap library, and request tracing via unique identifiers.
The system is built to handle errors at multiple layers—from database repositories to transport handlers—while maintaining a clean separation between internal error logic and external API responses.
Logging System Architecture
The logging system is based on the uber-go/zap library and is configured to support both development and production environments. It provides structured logging with automatic file rotation (based on timestamps) and console output.
Logger Initialization and Configuration
The logger is initialized in the application entry point using settings defined in the global configuration. It supports environment-based levels: DebugLevel for development and InfoLevel for production.
Sources: internal/core/logger/logger.go:50-65, internal/core/config/config.go:34-36, cmd/app/main.go:55-63
Context-Aware Logging
The service uses a context-aware logging pattern. A logger instance, often enriched with request-specific fields like request_id, is injected into the Go context.Context via middleware. This allows any downstream component (service, repository) to retrieve the logger and log messages that are automatically correlated with the specific HTTP request.
Sources: internal/core/logger/logger.go:24-35, internal/core/middleware/middleware.go:66-77
The diagram shows how the logger is passed through the request lifecycle to maintain traceability.
Sources: internal/core/middleware/middleware.go:66-77, internal/core/logger/logger.go:29-35
Error Handling Framework
The project utilizes a structured approach to error handling, defining common sentinel errors and a dedicated handler for mapping these errors to HTTP responses.
Sentinel Errors
Common domain-agnostic errors are defined in the core/errors package to be reused across different features.
| Error Variable | Description |
|---|---|
ErrNotFound | Resource was not found. |
ErrUnauthorized | User is not authenticated. |
ErrForbidden | User lacks necessary permissions. |
ErrConflict | Resource state conflict (e.g., duplicate entry). |
ErrBadRequest | Invalid input or request format. |
Sources: internal/core/errors/errors.go:5-11
HTTP Response Mapping
The HTTPResponseHandler is responsible for translating internal errors into the appropriate HTTP status codes and JSON error bodies.
This flow illustrates the logic within the ErrorResponse method that maps error types to HTTP statuses.
Sources: internal/core/response/response.go:42-65
Middleware Components
Several middleware components integrate logging and error handling into the HTTP pipeline.
Trace and Recoverer Middleware
- Trace Middleware: Logs the start and end of every HTTP request, including the method, URL, status code, and latency.
- Recoverer Middleware: Catches unexpected panics during request execution, logs the panic details, and returns a 500 Internal Server Error to the client to prevent the entire application from crashing.
Sources: internal/core/middleware/middleware.go:81-112
Middleware Functionality Summary
| Middleware | Description | Source |
|---|---|---|
RequestID | Generates or propagates X-Request-ID header for tracing. | internal/core/middleware/middleware.go:53-64 |
Logger | Enriches the logger with request_id and url, then stores it in context. | internal/core/middleware/middleware.go:66-77 |
Trace | Logs request latency and status codes. | internal/core/middleware/middleware.go:81-100 |
Recoverer | Handles panics and converts them to error responses. | internal/core/middleware/middleware.go:102-114 |
Implementation Example: Error Logging in Services
When an error occurs in a service (e.g., during a token refresh), the service retrieves the logger from the context to record the event before returning the error.
func (s *AuthService) Refresh(ctx context.Context, refreshToken string) (*LoginResult, error) {
log := logger.FromContext(ctx)
userID, err := s.refreshRepo.GetUserIDByToken(ctx, refreshToken)
if err != nil {
log.Warn("refresh token invalid or expired")
return nil, ErrInvalidRefreshToken
}
// ...
}
Sources: internal/features/auth/service/refresh.go:17-23
Conclusion
The error handling and logging system in the music service provides a robust foundation for observability and reliability. By combining structured zap logging with context propagation and a centralized HTTP response handler, the project ensures that developers can easily track request flows and that users receive consistent feedback when errors occur.