feat(flutter/api): dio client with Bearer interceptor + ApiError
ApiError.fromDio handles both server envelope shapes: {"error":"code"}
(admin endpoints) and {"error":{"code","message"}} (most others). Same
dual-shape problem the web apiFetch already solves. Token comes from a
resolver function so the auth provider can swap implementations
without touching the client.
ErrorCopy is a lazy singleton over assets/error-copy.json with the
same fallback chain web uses (specific code -> unknown -> hard-coded).
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
class ApiError implements Exception {
|
||||
ApiError({required this.code, required this.message, required this.status});
|
||||
|
||||
final String code;
|
||||
final String message;
|
||||
final int status;
|
||||
|
||||
factory ApiError.fromDio(DioException e) {
|
||||
if (e.type == DioExceptionType.connectionError ||
|
||||
e.type == DioExceptionType.connectionTimeout) {
|
||||
return ApiError(code: 'connection_refused', message: 'Connection refused', status: 0);
|
||||
}
|
||||
final response = e.response;
|
||||
final data = response?.data;
|
||||
if (data is Map<String, dynamic>) {
|
||||
final field = data['error'];
|
||||
if (field is String) {
|
||||
return ApiError(code: field, message: field, status: response?.statusCode ?? 0);
|
||||
}
|
||||
if (field is Map<String, dynamic>) {
|
||||
final code = field['code']?.toString() ?? 'unknown';
|
||||
final msg = field['message']?.toString() ?? code;
|
||||
return ApiError(code: code, message: msg, status: response?.statusCode ?? 0);
|
||||
}
|
||||
}
|
||||
final status = response?.statusCode ?? 0;
|
||||
if (status == 401) return ApiError(code: 'unauthenticated', message: 'unauthenticated', status: status);
|
||||
if (status == 404) return ApiError(code: 'not_found', message: 'not_found', status: status);
|
||||
return ApiError(code: 'unknown', message: e.message ?? 'unknown', status: status);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user