API Error Parser Plus
A robust and type-safe library for parsing API responses and converting error codes into user-friendly messages with comprehensive error handling and validation.
- API response description
- New API Format (v0.2.0+)
- New Features
- Version
- How it works
- Configuration
- Migration Guide
- License
API response description
The library supports both legacy and new API response formats with enhanced validation and type safety.
New API Format (v0.2.0+)
Starting from version 0.2.0, the library supports a simplified API format:
Successful Response
Successful responses now return data directly without a "data" wrapper:
{
"id": 1,
"userName": "Tom",
"age": 21
}
Error Response
Error responses contain an "errors" field in the root:
{
"errors": [
{
"code": "insufficient_funds",
"target": "common",
"message": "User has insufficient balance"
},
{
"code": "invalid_punctuation",
"target": "field",
"source": {
"field": "userPassword"
},
"message": "Password missing punctuation character"
}
]
}
Legacy Format Support
The library still supports the legacy format for backward compatibility:
{
"data": [
{
"id": 1,
"userName": "Tom",
"age": 21
}
],
"errors": [
{
"code": "insufficient_funds",
"target": "common",
"message": "User has insufficient balance"
}
]
}
}
] }
# New Features
## 🚀 Enhanced Type Safety
- **ErrorTarget enum**: Strongly typed target validation (`ErrorTarget.field`, `ErrorTarget.common`)
- **ParseResult<T>**: Comprehensive result handling for safer parsing operations
- **Strict validation**: Required field validation and format checking
## 🛡️ Robust Error Handling
- **Safe JSON parsing**: `fromJsonSafe()` methods with detailed error reporting
- **Validation rules**: Automatic validation of error structure and required fields
- **Graceful degradation**: Backward compatibility with legacy error handling
## ⚙️ Flexible Configuration
```dart
// Different configurations for different environments
ApiParserConfig.production // Minimal logging, graceful error handling
ApiParserConfig.debug // Detailed logging, non-strict mode
ApiParserConfig.testing // Full logging, strict validation
// Custom configuration
ApiParserConfig(
enableLogging: true,
strictMode: false,
logPrefix: '[MyApp]'
)
🔍 Advanced Error Analysis
- Unknown code detection:
getUnknownErrorCodes()to identify unmapped error codes - Structure validation:
isValidErrorMessage()to verify error format - Enhanced debugging: Detailed error messages and source tracking
Version
0.2.0 (Major API format update with simplified response handling)
How it works
The library provides enhanced interfaces and validation for server responses.
Basic Usage
final apiParser = ApiParser<String>(
errorMessages: {
'insufficient_funds': 'Insufficient balance',
'invalid_password': 'Invalid password',
},
fieldErrorMessages: {
'email': {
'invalid_format': 'Please enter a valid email',
},
'password': {
'too_short': 'Password must be at least 8 characters',
}
},
defaultErrorMessage: 'Something went wrong',
config: ApiParserConfig.production, // Choose appropriate config
);
// Parse response with enhanced error handling
final response = ApiResponseEntity.fromJson(jsonData, fromJson: User.fromJson);
final result = apiParser.parse(response);
// Type-safe result handling
switch (result.runtimeType) {
case ApiParserSuccessResponse:
final successResult = result as ApiParserSuccessResponse;
// Handle success
break;
case ApiParserErrorResponse:
final errorResult = result as ApiParserErrorResponse;
// Handle errors with enhanced information
break;
case ApiParserEmptyResponse:
// Handle empty response
break;
}
Safe Parsing with ParseResult
// Use safe parsing for better error handling
final parseResult = ApiResponseEntity.fromJsonSafe<User>(
jsonData,
fromJson: User.fromJson,
config: ApiParserConfig.debug
);
if (parseResult.isSuccess) {
final response = parseResult.dataOrThrow;
// Process successful response
} else {
final error = parseResult as ParseError;
print('Parsing failed: ${error.message}');
if (error.cause != null) {
print('Cause: ${error.cause}');
}
}
Enhanced Error Analysis
// Check for unknown error codes
final unknownCodes = apiParser.getUnknownErrorCodes(errors);
if (unknownCodes.isNotEmpty) {
print('Unknown error codes detected: $unknownCodes');
}
// Validate error structure
for (final error in errors) {
if (!apiParser.isValidErrorMessage(error)) {
print('Invalid error structure: $error');
}
}
Configuration
ApiParserConfig Options
class ApiParserConfig {
final bool enableLogging; // Enable detailed logging
final bool strictMode; // Throw exceptions on parsing errors
final String logPrefix; // Custom log prefix
}
Predefined Configurations
ApiParserConfig.production: Minimal logging, graceful error handlingApiParserConfig.debug: Detailed logging for developmentApiParserConfig.testing: Strict validation for tests
Migration Guide
Breaking Changes in v0.0.4
1. ErrorTarget Type Change
// Before
if (error.target == "field") { ... }
// After
if (error.target == ErrorTarget.field) { ... }
2. Enhanced Constructor
// Before
ApiParser(
errorMessages: {...},
defaultErrorMessage: "Error"
);
// After
ApiParser(
errorMessages: {...},
defaultErrorMessage: "Error",
config: ApiParserConfig.production // New optional parameter
);
3. Safe Parsing Methods
// Old method still works for backward compatibility
final response = ApiResponseEntity.fromJson(json);
// New recommended approach
final parseResult = ApiResponseEntity.fromJsonSafe(json);
if (parseResult.isSuccess) {
final response = parseResult.dataOrThrow;
}
Recommended Migration Steps
- Update imports: Add new exports to your imports
- Replace string comparisons: Use
ErrorTargetenum instead of string comparisons - Add configuration: Specify appropriate
ApiParserConfigfor your environment - Consider safe parsing: Migrate to
fromJsonSafemethods for better error handling - Update tests: Use enhanced validation and error detection features
License
ApiParser is released under the MIT license. See LICENSE for details.