api_error_parser_plus 0.3.0 copy "api_error_parser_plus: ^0.3.0" to clipboard
api_error_parser_plus: ^0.3.0 copied to clipboard

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 Error Parser Plus #

License: MIT

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 #

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
  • Meta field support: Optional metadata in errors for dynamic parameters (v0.3.0+)

🎯 Meta Field Support (v0.3.0+) #

  • Dynamic error metadata: Optional meta field with arbitrary structure
  • Type-safe accessors: metaInt(), metaDouble(), metaStr(), metaBool(), metaMap()
  • Template interpolation: interpolate() method for dynamic message generation
  • Backward compatible: Existing code works without changes

Version #

0.3.0 (Meta field support for dynamic error parameters)

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}');
  }
}

Working with Meta Field (v0.3.0+) #

// Error with metadata from backend
// {
//   "code": "too_short",
//   "target": "field",
//   "source": {"field": "password"},
//   "meta": {"min": 8, "max": 20}
// }

final error = errors.first;

// Type-safe meta access
final minLength = error.metaInt('min') ?? 8;  // Returns 8
final maxLength = error.metaInt('max') ?? 20; // Returns 20

// Template interpolation
final template = "Пароль должен быть от {min} до {max} символов";
final message = error.interpolate(template);
// Result: "Пароль должен быть от 8 до 20 символов"

// Check if meta exists
if (error.meta != null) {
  print('Error has metadata: ${error.meta}');
}

See Meta Usage Guide for detailed examples.

Enhanced Error Analysis #

// Check for unknown error codes
final unknownCodes = apiParser.getUnknownErrorCodes(errors);
if (unknownCodes.isNotEmpty) {
  print('Unknown error codes detected: $unknownCodes');
}

## Enhanced Error Analysis

```dart
// 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 handling
  • ApiParserConfig.debug: Detailed logging for development
  • ApiParserConfig.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;
}
  1. Update imports: Add new exports to your imports
  2. Replace string comparisons: Use ErrorTarget enum instead of string comparisons
  3. Add configuration: Specify appropriate ApiParserConfig for your environment
  4. Consider safe parsing: Migrate to fromJsonSafe methods for better error handling
  5. Update tests: Use enhanced validation and error detection features

License #

ApiParser is released under the MIT license. See LICENSE for details.

3
likes
150
points
368
downloads

Publisher

unverified uploader

Weekly Downloads

A robust and type-safe library for parsing API responses and converting error codes into user-friendly messages with comprehensive error handling and validation.

Homepage

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

flutter

More

Packages that depend on api_error_parser_plus