feat: Add comprehensive documentation for error handling, testing strategy, monitoring, and development workflow

- Add Enhanced Error Handling section with error codes (VALIDATION_FAILED, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, ALREADY_EXISTS, INTERNAL_ERROR, RATE_LIMITED), standardized JSON response format, and field-specific validation error structure
- Add Testing Strategy section with integration test coverage for API endpoints/authentication/RBAC/services, test structure example with setupTest
This commit is contained in:
nutcas3
2026-04-20 18:19:36 +03:00
parent a6ec720df3
commit 0d8c1a8098
2 changed files with 215 additions and 0 deletions
+84
View File
@@ -295,6 +295,90 @@ Strict-Transport-Security: max-age=31536000; includeSubDomains
Plus request size limit (10MB), request timeout (30s), and CORS configuration.
### Enhanced Error Handling
Comprehensive error handling system with standardized error responses:
**Error Codes**:
- `VALIDATION_FAILED` - Input validation errors with field-specific details
- `UNAUTHORIZED` - Authentication failures
- `FORBIDDEN` - Authorization/permission errors
- `NOT_FOUND` - Resource not found
- `ALREADY_EXISTS` - Duplicate resource attempts
- `INTERNAL_ERROR` - Server-side errors
- `RATE_LIMITED` - Rate limiting violations
**Error Response Format**:
```json
{
"error": "Human-readable error message",
"code": "ERROR_CODE",
"details": "Detailed error context",
"timestamp": "2024-01-01T00:00:00Z"
}
```
**Validation Errors**:
```json
{
"error": "Validation failed",
"code": "VALIDATION_FAILED",
"errors": [
{
"field": "email",
"message": "must be a valid email address",
"value": "invalid-email"
}
]
}
```
### Testing Strategy
**Integration Tests**:
- Full API endpoint testing with in-memory SQLite
- Authentication and RBAC testing with mock users
- Service layer testing for all major services
- Error handling validation across all endpoints
**Test Coverage**:
- Authentication flows (login, token validation, refresh)
- RBAC permissions (admin, operator, viewer roles)
- Service operations (CRUD, validation, error handling)
- Error scenarios (invalid input, missing resources, permissions)
**Test Structure**:
```go
func TestAuthenticationEndpoints(t *testing.T) {
ts := setupTest(t)
defer ts.DB.Close()
t.Run("Login with valid credentials", func(t *testing.T) {
// Test implementation
})
}
```
### Monitoring & Observability
**Metrics Collection**:
- Request latency and throughput
- Error rates by endpoint and error type
- Authentication success/failure rates
- Database query performance
- JWT token validation metrics
**Health Checks**:
- `/health` - Basic health status
- `/ready` - Readiness probe (dependencies check)
- `/live` - Liveness probe (service health)
**Logging**:
- Structured JSON logging
- Request correlation IDs
- Error stack traces in debug mode
- Security event logging
### Rate Limiting
Tiered limits protect against abuse (see `@/Users/nutcase/Downloads/telecom-platform-starter/apps/api-server/internal/middleware/ratelimit.go`):
+131
View File
@@ -256,6 +256,80 @@ Configure webhooks to receive real-time events:
}
```
## Development Workflow
### Running Tests
```bash
# Run all tests
make test
# Run API server tests
cd apps/api-server && go test ./...
# Run integration tests
cd apps/api-server && go test ./internal/handlers -v
# Run service layer tests
cd apps/api-server && go test ./internal/services -v
# Run with coverage
cd apps/api-server && go test -cover ./...
# Run specific test
cd apps/api-server && go test ./internal/handlers -run TestAuthenticationEndpoints -v
```
### Code Quality
```bash
# Format code
cd apps/api-server && go fmt ./...
cd apps/web-dashboard && pnpm format
# Lint code
cd apps/api-server && golangci-lint run
cd apps/web-dashboard && pnpm lint
# Run static analysis
cd apps/api-server && go vet ./...
```
### Database Operations
```bash
# Run database migrations
make db-migrate
# Reset database (development only)
make db-reset
# Create test data
make db-seed
# View database logs
docker-compose logs mongodb
docker-compose logs postgres
```
### Monitoring & Debugging
```bash
# View service logs
make logs
make logs-api-server
make logs-charging-engine
# Monitor metrics
curl http://localhost:8000/metrics
curl http://localhost:8080/metrics
# Check health endpoints
curl http://localhost:8000/health
curl http://localhost:8000/ready
curl http://localhost:8000/live
```
## Common Commands
```bash
@@ -265,6 +339,10 @@ make verify # Check services
make free5gc-logs # View free5GC logs
make docker-build # Build Docker images
make clean # Remove build artifacts
make test # Run all tests
make logs # View all service logs
make dev-ui # Start web dashboard in dev mode
make dev-api # Start API server in dev mode
```
## Troubleshooting
@@ -288,6 +366,59 @@ chmod +x scripts/*.sh
- Check connection strings in `.env`
- For PostgreSQL: confirm `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME` are set
## Recent Improvements
### Enhanced Error Handling
The platform now includes comprehensive error handling with standardized error responses:
- **Structured error codes** for different error types
- **Field-specific validation errors** with detailed messages
- **Consistent error response format** across all endpoints
- **Request correlation IDs** for debugging
Example error response:
```json
{
"error": "Validation failed",
"code": "VALIDATION_FAILED",
"details": "Invalid input data",
"errors": [
{
"field": "email",
"message": "must be a valid email address",
"value": "invalid-email"
}
]
}
```
### Comprehensive Testing
The platform now has extensive test coverage:
- **Integration tests** for all API endpoints
- **Service layer tests** for business logic
- **Authentication and RBAC testing** with mock users
- **Error handling validation** across all scenarios
Run tests with:
```bash
cd apps/api-server && go test ./internal/handlers -v
cd apps/api-server && go test ./internal/services -v
```
### Role-Based Access Control (RBAC)
Enhanced RBAC implementation using Casbin:
- **Policy-based permissions** with fine-grained control
- **Default roles**: admin, operator, viewer
- **Dynamic policy management** via API
- **Fallback role middleware** for compatibility
Example policy check:
```go
allowed, err := casbinSvc.CheckPermission(userID, "/v1/services", "GET")
```
## Next Steps
- **Architecture**: See [`ARCHITECTURE.md`](./ARCHITECTURE.md) for system design, RBAC, and security.