Flutter错误解析插件api_error_parser_plus的使用

Flutter 错误解析插件 api_error_parser_plus 的使用


API error parser plus

License: BSD

一个用于解析 API 响应并将错误码转换为用户可读消息的库。


API 响应描述

假定响应将符合以下规范。

每个来自服务器的错误应该以以下格式出现:

  • code: 错误的唯一代码。用于从字典中识别错误。
  • target: 某种错误范围。
  • field: 与特定字段相关的错误。
  • common: 与整个请求相关的错误。
  • `message (可选): 供开发者使用的错误信息(仅用于调试目的)。
  • **source (可选)**: 包含额外数据的容器。任意结构:(field: 资源对象属性名称。如果target设置为field` 则必填)。

示例:

{
  "data": [
    {
      "id": 1,
      "userName": "Tom",
      "age": 21
    },
    {
      "id": 2,
      "userName": "Bob",
      "age": 22
    }
  ],
  "errors": [
    {
      "code": "insufficient_funds",
      "target": "common",
      "message": "Hi Nick, it seems that user has empty balance"
    },
    {
      "code": "invalid_punctuation",
      "target": "field",
      "source": {
        "field": "userPassword"
      },
      "message": "Hi Vova, it seems that the password provided is missing a punctuation character"
    },
    {
      "code": "invalid_password_confirmation",
      "target": "field",
      "source": {
        "field": "userPassword",
        "someAdditionalData": "bla bla bla"
      },
      "message": "Hi Lesha, it seems that the password and password confirmation fields do not match"
    }
  ]
}

分页

在服务器响应中应该包含分页对象,格式如下:

  • currentPage: 当前返回的页数。
  • totalPage: 总页数。
  • totalRecord: 总记录数。
  • limit: 每页的项目数量。

示例:

{
  "data": [
    {
      "id": 1
    },
    {
      "id": 2
    }
  ],
  "pagination": {
    "currentPage": 3,
    "totalPage": 10,
    "totalRecord": 92,
    "limit": 10
  }
}

版本

0.0.3


如何工作

该库提供了现成的接口来处理服务器响应,这些接口必须符合传递给参数的对象。

要初始化 ErrorParser,你必须在构造函数中传递以下内容:

  • errorMessages:
    • <code>Map<String, E></code> - 键是错误代码,值是显示的消息。
    • `defaultErrorMessage: E - 未知错误的消息。

API 解析器描述:

  • <code>parse(ApiParserResponse<T> response)</code> - 返回 <code>ApiParserResponse</code> 状态:成功、空或错误。
  • <code>getParserResponse(ApiResponse<T> response)</code> - 解析服务器响应对象并返回处理结果。
  • <code>getErrors(List<ErrorMessage> errors)</code> - 返回已处理错误的列表。
  • <code>getMessageFromCode(String errorCode)</code> - 返回与此错误代码关联的消息。
  • <code>getMessage(ErrorMessage errorMessage)</code> - 返回已处理的错误。
  • <code>getFirstMessage(List<ErrorMessage> errors)</code> - 返回列表中的第一个已处理错误。
  • <code>getFieldMessageFromCode(String field, String errorCode)</code> - 返回列表中的第一个已处理错误。

Dart

// 初始化 ErrorParser
final apiParser = ApiParser({
  CODE.ERROR_CODE: Message.ERROR_MESSAGE,
}, Message.DEFAULT);

// 解析服务器响应
final ParserResponse<UserEntity> parserResponse = apiParser.getParserResponse(serverResponse);

// 使用 parse 方法解析响应
final ApiParserResponse<UserEntity> apiParserResponse = apiParser.parse(serverResponse); 

// 根据响应类型执行不同的操作
switch (apiParserResponse.runtimeType) {
  case ApiParserEmptyResponse: {
    // 处理空响应
    break;
  }
  case ApiParserErrorResponse: {
    // 处理错误响应
    break;
  }
  case ApiParserSuccessResponse: {
    // 处理成功响应
    break;
  }
}

更多关于Flutter错误解析插件api_error_parser_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter错误解析插件api_error_parser_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


api_error_parser_plus 是一个用于 Flutter 的插件,旨在帮助开发者在处理 API 请求时,更方便地解析和处理错误。这个插件通常用于在应用与后端 API 交互时,将 API 返回的错误信息解析为易于理解的格式,并根据需要采取相应的处理措施。

安装

首先,你需要在 pubspec.yaml 文件中添加 api_error_parser_plus 依赖:

dependencies:
  flutter:
    sdk: flutter
  api_error_parser_plus: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

基本用法

api_error_parser_plus 插件的核心功能是将 API 返回的错误信息解析为统一的格式,通常是一个 ApiError 对象。以下是一个简单的使用示例:

import 'package:api_error_parser_plus/api_error_parser_plus.dart';

void main() {
  // 假设这是从API返回的错误响应
  final Map<String, dynamic> errorResponse = {
    "error": {
      "code": "INVALID_REQUEST",
      "message": "The request is invalid.",
      "details": [
        {"field": "email", "message": "Invalid email address."}
      ]
    }
  };

  // 解析错误
  final ApiError apiError = ApiErrorParser.parse(errorResponse);

  // 获取错误信息
  print('Error Code: ${apiError.code}'); // 输出: Error Code: INVALID_REQUEST
  print('Error Message: ${apiError.message}'); // 输出: Error Message: The request is invalid.

  // 处理错误详情
  for (var detail in apiError.details) {
    print('Field: ${detail.field}, Message: ${detail.message}');
    // 输出: Field: email, Message: Invalid email address.
  }
}

ApiError 结构

ApiError 通常包含以下字段:

  • code: 错误的唯一标识符或错误码。
  • message: 错误的描述信息。
  • details: 错误的详细信息列表,通常包含字段相关的错误信息。

自定义错误解析

你可以通过继承 ApiErrorParser 类并重写 parse 方法来自定义错误的解析逻辑。例如:

class CustomApiErrorParser extends ApiErrorParser {
  @override
  ApiError parse(Map<String, dynamic> json) {
    // 自定义解析逻辑
    return ApiError(
      code: json['custom_error']['code'],
      message: json['custom_error']['message'],
      details: [], // 根据需要解析details
    );
  }
}

处理不同类型的错误

在实际应用中,你可能会遇到不同类型的错误(如网络错误、服务器错误、业务逻辑错误等)。api_error_parser_plus 可以帮助你将所有这些错误统一处理:

try {
  // 发起API请求
  final response = await http.get('https://example.com/api');
  if (response.statusCode == 200) {
    // 处理成功响应
  } else {
    // 解析错误响应
    final error = ApiErrorParser.parse(json.decode(response.body));
    // 处理错误
    handleError(error);
  }
} catch (e) {
  // 处理其他类型的错误(如网络错误)
  handleError(ApiError(code: 'NETWORK_ERROR', message: e.toString()));
}
回到顶部