fromError<S> static method
Creates a failure result from a DioException or any exception object.
Extracts error message from response body following TsdTech API conventions:
-
Checks
error.messageorerror.title -
Falls back to
data['message']ordata['detail'] -
Handles list responses by taking first element
-
Falls back to exception.toString() as last resort
-
exceptionOrError: The exception or error object to convert -
Returns: A ValueResult with extracted error message
Implementation
static ValueResult<S> fromError<S>(dynamic exceptionOrError) {
String? title;
String errorMessage = 'Ocorreu um erro desconhecido.';
try {
final data = exceptionOrError?.response?.data;
final error = data?['error'];
if (error is Map) {
final Map<String, dynamic> errorMap = error as Map<String, dynamic>;
final Map<String, dynamic>? dataMap = data as Map<String, dynamic>?;
final String? titleValue =
errorMap['title'] as String? ?? dataMap?['title'] as String?;
title = titleValue;
final String errorMsg =
(errorMap['message'] ?? dataMap?['message'] ?? errorMessage)
as String;
errorMessage = errorMsg;
} else if (error is String) {
errorMessage = error;
} else if (data is Map) {
if (data['message'] is String) {
title = data['title'] as String?;
errorMessage = data['message'] as String;
} else if (data['detail'] is String) {
errorMessage = data['detail'] as String;
} else if (data['detail'] is List &&
(data['detail'] as List).isNotEmpty) {
final first = (data['detail'] as List).first;
errorMessage = first is String ? first : first.toString();
}
}
if (errorMessage == 'Ocorreu um erro desconhecido.' &&
(exceptionOrError is Exception || exceptionOrError is Error)) {
errorMessage = exceptionOrError.toString();
} else if (errorMessage == 'Ocorreu um erro desconhecido.' &&
exceptionOrError?.message != null) {
errorMessage = exceptionOrError.message.toString();
}
} catch (_) {
if (exceptionOrError != null) {
errorMessage = exceptionOrError.toString();
}
}
return ValueResult<S>.failure(errorMessage, title: title);
}