api_error_parser_plus 0.1.0 copy "api_error_parser_plus: ^0.1.0" to clipboard
api_error_parser_plus: ^0.1.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 assumes that API responses follow these specifications with enhanced validation and type safety.

Each error from server should be in the following format:

  • code: a unique error code (non-empty string). Used to identify error from the dictionary.
  • target: error scope with strict validation
    • field - error related to a specific field (requires source.field)
    • common - error related to the whole request
  • message (OPTIONAL): error message for developers (debug purposes only)
  • source (OPTIONAL): container for additional data
    • field: resource object attribute name (required when target is "field")

Example with enhanced validation:

{
  "data": [
    {
      "id": 1,
      "userName": "Tom",
      "age": 21
    }
  ],
  "errors": [
    {
      "code": "insufficient_funds",
      "target": "common",
      "message": "User has insufficient balance"
    },
    {
      "code": "invalid_punctuation",
      "target": "field",
      "source": {
        "field": "userPassword"
      },
      "message": "Password missing punctuation character"
    }
  ]
}

New Features #

🚀 Enhanced Type Safety #

  • ErrorTarget enum: Strongly typed target validation (ErrorTarget.field, ErrorTarget.common)
  • ParseResult: 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 #

// 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.1.0 (Enhanced with type safety and validation, pagination removed)

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 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
0
points
21
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

License

unknown (license)

Dependencies

flutter

More

Packages that depend on api_error_parser_plus