loading state and error handling refactor
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:jiffy/jiffy.dart';
|
||||
import '../apiError.dart';
|
||||
|
||||
import '../apiRequest.dart';
|
||||
import '../errors/network_exception.dart';
|
||||
import '../errors/parse_exception.dart';
|
||||
import '../errors/server_exception.dart';
|
||||
|
||||
abstract class MhslApi<T> extends ApiRequest {
|
||||
String subpath;
|
||||
@@ -15,18 +20,38 @@ abstract class MhslApi<T> extends ApiRequest {
|
||||
T assemble(String raw);
|
||||
|
||||
Future<T> run() async {
|
||||
var endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
|
||||
final endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
|
||||
|
||||
var data = await request(endpoint);
|
||||
if(data == null) {
|
||||
throw ApiError('Request could not be dispatched!');
|
||||
final http.Response data;
|
||||
try {
|
||||
final raw = await request(endpoint);
|
||||
if (raw == null) {
|
||||
throw const NetworkException(
|
||||
userMessage: 'Keine Antwort vom MHSL-Dienst erhalten.',
|
||||
technicalDetails: 'mhsl request returned null',
|
||||
);
|
||||
}
|
||||
data = raw;
|
||||
} on SocketException catch (e) {
|
||||
throw NetworkException(technicalDetails: 'mhsl $subpath: ${e.message}');
|
||||
} on TimeoutException catch (e) {
|
||||
throw NetworkException.timeout(technicalDetails: 'mhsl $subpath: $e');
|
||||
} on http.ClientException catch (e) {
|
||||
throw NetworkException(technicalDetails: 'mhsl $subpath: ${e.message}');
|
||||
}
|
||||
|
||||
if(data.statusCode > 299) {
|
||||
throw ApiError('Non 200 Status code from mhsl services: $subpath: ${data.statusCode}');
|
||||
if (data.statusCode > 299) {
|
||||
throw ServerException(
|
||||
statusCode: data.statusCode,
|
||||
technicalDetails: 'mhsl $subpath HTTP ${data.statusCode}',
|
||||
);
|
||||
}
|
||||
|
||||
return assemble(utf8.decode(data.bodyBytes));
|
||||
try {
|
||||
return assemble(utf8.decode(data.bodyBytes));
|
||||
} catch (e) {
|
||||
throw ParseException(technicalDetails: 'mhsl $subpath assemble: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static String dateTimeToJson(DateTime time) => Jiffy.parseFromDateTime(time).format(pattern: 'yyyy-MM-dd HH:mm:ss');
|
||||
|
||||
Reference in New Issue
Block a user