What We’ll Build
We’ll create a simple user management API with:- User retrieval endpoint
- Error handling for missing users
- Bilingual response support
- Both exception-based and functional error handling patterns
Method 1: StatusFlow Function Approach
This approach uses theStatusFlow function to generate responses and the statusFlowMiddleware for error handling.
Create server.js (or server.ts)
Create a file called
server.js with the following code:The
statusFlowMiddleware intercepts errors passed to next() and automatically generates StatusFlow responses based on the error’s code property.Method 2: Exception-Based Approach
This approach uses exception classes and thehttpErrorMiddleware for a more traditional error handling pattern.
Understanding StatusFlow Components
StatusFlow Function
TheStatusFlow function generates rich response objects:
StatusFlowCodes
Use constants instead of magic numbers:Exception Classes
All exception classes accept:BadRequestException(400)UnauthorizedException(401)ForbiddenException(403)NotFoundException(404)ConflictException(409)InternalServerErrorException(500)
Key Differences Between Approaches
| Feature | StatusFlow Function | Exception Classes |
|---|---|---|
| Middleware | statusFlowMiddleware | httpErrorMiddleware |
| Response Format | Rich with info object | Simple status, message, details |
| Bilingual Support | Built-in with lang parameter | Not included |
| Error Handling | Pass object to next() with code | Throw exception classes |
| Success Responses | Use StatusFlow() with 2xx codes | Use createSuccessResponse() |
| Use Case | Bilingual APIs, rich error context | Traditional REST APIs |
You can mix both approaches in the same application, but use only one middleware at a time to avoid conflicts.
Best Practices
- Choose one approach - Pick either StatusFlow function or exceptions for consistency
- Language detection - Read from headers (
x-lang) or user preferences - Use StatusFlowCodes - Avoid magic numbers for status codes
- Add context with
extra- Include relevant data in error responses - Register middleware last - Error middleware must come after all routes
- Wrap async routes - Use try/catch in async route handlers
Next Steps
Now that you have a working StatusFlow API, explore:API Reference
Detailed documentation of all functions and classes
Examples
More advanced usage patterns and real-world examples