api_error_parser_plus 0.2.0 copy "api_error_parser_plus: ^0.2.0" to clipboard
api_error_parser_plus: ^0.2.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.

example/example.md

API Error Parser Plus - Быстрый старт #

Библиотека для типобезопасной обработки API ответов и преобразования кодов ошибок в пользовательские сообщения.

📦 Установка #

dependencies:
  api_error_parser_plus: ^0.2.0

🚀 Новый формат API (v0.2.0+) #

Успешные ответы #

Данные приходят напрямую без обертки "data":

{"id": 1, "userName": "Tom", "age": 21}

Ответы с ошибками #

Содержат поле "errors" в корне:

{
  "errors": [
    {
      "code": "insufficient_funds",
      "target": "common",
      "message": "User has insufficient balance"
    }
  ]
}

💻 Быстрая интеграция #

1. Создайте модель данных #

class User {
  final int id;
  final String userName;
  final int age;

  User({required this.id, required this.userName, required this.age});

  factory User.fromJson(Map<String, dynamic> json) => User(
    id: json['id'],
    userName: json['userName'], 
    age: json['age'],
  );
}

2. Настройте парсер #

import 'package:api_error_parser_plus/api_error_parser_plus.dart';

final apiParser = ApiParser(
  errorMessages: {
    'insufficient_funds': 'Недостаточно средств',
    'invalid_password': 'Неверный пароль',
    'user_not_found': 'Пользователь не найден',
  },
  fieldErrorMessages: {
    'email': {
      'invalid_format': 'Введите корректный email',
      'already_taken': 'Email уже используется',
    },
    'password': {
      'too_short': 'Пароль слишком короткий',
      'no_uppercase': 'Пароль должен содержать заглавные буквы',
    }
  },
  defaultErrorMessage: 'Произошла неизвестная ошибка',
  config: ApiParserConfig.production,
);

3. Обработка ответов сервера #

// Парсинг JSON ответа с типобезопасностью
final parseResult = ApiResponseEntity.fromJsonSafe<User>(
  jsonResponse,
  fromJson: User.fromJson,
  config: ApiParserConfig.production,
);

if (parseResult.isSuccess) {
  final response = parseResult.dataOrThrow;
  
  // Анализ результата
  final result = apiParser.parse(response);
  
  switch (result.runtimeType) {
    case ApiParserSuccessResponse:
      final successResult = result as ApiParserSuccessResponse<User, String>;
      print('Успех: ${successResult.data?.userName}');
      break;
      
    case ApiParserErrorResponse:
      final errorResult = result as ApiParserErrorResponse<User, String>;
      // Обработка ошибок с локализованными сообщениями
      errorResult.errors?.forEach((error) {
        print('Ошибка: ${error.message}');
        if (error.source?.field != null) {
          print('Поле: ${error.source!.field}');
        }
      });
      break;
      
    case ApiParserEmptyResponse:
      print('Пустой ответ');
      break;
  }
} else {
  final error = parseResult as ParseError;
  print('Ошибка парсинга: ${error.message}');
}

🛠️ Расширенные возможности #

Конфигурации для разных сред #

// Production: минимальное логирование
ApiParserConfig.production

// Debug: подробное логирование
ApiParserConfig.debug  

// Testing: строгая валидация
ApiParserConfig.testing

// Кастомная конфигурация
ApiParserConfig(
  enableLogging: true,
  strictMode: false,
  logPrefix: '[MyApp]'
)

Анализ неизвестных ошибок #

// Найти неизвестные коды ошибок
final unknownCodes = apiParser.getUnknownErrorCodes(errors);
if (unknownCodes.isNotEmpty) {
  print('Неизвестные коды: $unknownCodes');
}

// Валидация структуры ошибок
for (final error in errors) {
  if (!apiParser.isValidErrorMessage(error)) {
    print('Невалидная структура: $error');
  }
}

Обработка полей с ошибками #

// Получить сообщение для конкретного поля
final emailError = apiParser.getFieldMessageFromCode('email', 'invalid_format');
print(emailError); // "Введите корректный email"

// Обработка ошибок по типу target
errors?.forEach((error) {
  switch (error.target) {
    case ErrorTarget.field:
      // Ошибки поля
      print('Поле ${error.source?.field}: ${error.message}');
      break;
    case ErrorTarget.common:
      // Общие ошибки
      print('Общая ошибка: ${error.message}');
      break;
  }
});

🔄 Миграция с предыдущих версий #

Обновите API формат #

  • Успешные ответы: уберите обертку {"data": ...}
  • Ответы с ошибками: оставьте {"errors": [...]}

Используйте новые методы #

// Старый способ
final response = ApiResponseEntity.fromJson(json);

// Новый способ (рекомендуется)
final result = ApiResponseEntity.fromJsonSafe(json);
final response = result.dataOrThrow;

📚 Полная документация #

Смотрите README.md для подробной документации и дополнительных примеров.

3
likes
160
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

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

flutter

More

Packages that depend on api_error_parser_plus