示例工程 ch13-network

ch13-network/lib/src/api_exception.dart

dart · 2.4 KB

/// 错误分类:网络层的第一职责是"把底层异常翻译成业务能处理的类型"。
///
/// 对照 Go:`net/http` 返回 `error`,你得自己 `errors.Is(err, context.DeadlineExceeded)`
/// 之类去分类;Dart 用异常,分类即子类。
library;
 
/// 所有网络/解析错误的基类。
sealed class ApiException implements Exception {
  const ApiException(this.message, {this.cause});
 
  final String message;
  final Object? cause;
 
  /// 给用户看的文案(不要把堆栈或英文异常直接丢给用户)。
  String get userMessage => switch (this) {
        NetworkException() => '网络不可用,请检查连接后重试',
        ApiTimeoutException() => '请求超时,请稍后重试',
        RequestCancelledException() => '请求已取消',
        HttpStatusException(:final statusCode) when statusCode == 401 => '登录已过期,请重新登录',
        HttpStatusException(:final statusCode) when statusCode == 404 => '请求的数据不存在',
        HttpStatusException(:final statusCode) when statusCode >= 500 => '服务器开小差了,请稍后重试',
        HttpStatusException() => '请求失败,请稍后重试',
        ParseException() => '数据格式错误,请升级到最新版本',
      };
 
  @override
  String toString() => '$runtimeType($message)';
}
 
/// 连不上(DNS 失败、连接被拒、断网)。
class NetworkException extends ApiException {
  const NetworkException(super.message, {super.cause});
}
 
/// 超时(连接、发送或接收)。
class ApiTimeoutException extends ApiException {
  const ApiTimeoutException(super.message, {super.cause});
}
 
/// 被主动取消(用户离开页面、点了取消)。
class RequestCancelledException extends ApiException {
  const RequestCancelledException([super.message = '请求已取消']);
}
 
/// 非 2xx 响应。
class HttpStatusException extends ApiException {
  const HttpStatusException(this.statusCode, this.body)
      : super('HTTP $statusCode');
 
  final int statusCode;
  final String body;
 
  bool get isClientError => statusCode >= 400 && statusCode < 500;
  bool get isServerError => statusCode >= 500;
 
  /// 5xx 和 429(限流)可以重试;4xx 重试没意义。
  bool get isRetryable => isServerError || statusCode == 429;
}
 
/// 响应能拿到,但不是合法 JSON / 结构不对。
class ParseException extends ApiException {
  const ParseException(super.message, {super.cause});
}