Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions lib/Business_Logic/Exceptions/exception_handlers.dart
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import 'package:flutter/material.dart';

import '../../Presentation/Components/snack_bar.dart';

enum ExceptionTypes {
socketException,
httpException,
formatException,
timeoutException
}
import 'dart:async';
import 'dart:io';

class ExceptionHandlers {
String typeOfException(ExceptionTypes exceptionTypes) {
switch (exceptionTypes) {
case ExceptionTypes.socketException:
return 'No internet connection.';
case ExceptionTypes.httpException:
return 'HTTP error occured.';
case ExceptionTypes.formatException:
return 'Invalid data format.';
case ExceptionTypes.timeoutException:
return 'Request timeout.';
getExceptionString(error) {
if (error is SocketException) {
return 'No internet connection.';
} else if (error is HttpException) {
return 'HTTP error occured.';
} else if (error is FormatException) {
return 'Invalid data format.';
} else if (error is TimeoutException) {
return 'Request timedout.';
} else if (error is BadRequestException) {
return error.message.toString();
} else if (error is UnAuthorizedException) {
return error.message.toString();
} else if (error is NotFoundException) {
return error.message.toString();
} else if (error is FetchDataException) {
return error.message.toString();
} else {
return 'Unknown error occured.';
}
}
}
Expand Down Expand Up @@ -56,4 +57,3 @@ class NotFoundException extends AppException {
NotFoundException([String? message, String? url])
: super(message, 'Page not found', url);
}

28 changes: 10 additions & 18 deletions lib/Data/API/base_client.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import 'dart:async';

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

import '../../Business_Logic/Exceptions/exception_handlers.dart';
import 'package:http/http.dart' as http;

class BaseClient {
static const int timeOutDuration = 35;
Expand All @@ -15,14 +15,8 @@ class BaseClient {
var response =
await http.get(uri).timeout(const Duration(seconds: timeOutDuration));
return _processResponse(response);
} on SocketException {
throw const SocketException('Socket exception');
} on TimeoutException {
throw ApiNotRespondingException('Server not responding.');
} on FormatException {
} on HttpException {
} catch (e) {
throw e.toString();
throw ExceptionHandlers().getExceptionString(e);
}
}

Expand All @@ -36,11 +30,9 @@ class BaseClient {
.timeout(const Duration(seconds: timeOutDuration));

return _processResponse(response);
} on SocketException {
} on TimeoutException {
throw ApiNotRespondingException('Server not responding.');
} on FormatException {
} on HttpException {}
} catch (e) {
throw ExceptionHandlers().getExceptionString(e);
}
}

//DELETE
Expand All @@ -54,13 +46,13 @@ class BaseClient {
var responseJson = response.body;
return responseJson;
case 400: //Bad request
throw BadRequestException(response.body);
throw BadRequestException(jsonDecode(response.body)['message']);
case 401: //Unauthorized
throw UnAuthorizedException(response.body);
throw UnAuthorizedException(jsonDecode(response.body)['message']);
case 403: //Forbidden
throw UnAuthorizedException(response.body);
throw UnAuthorizedException(jsonDecode(response.body)['message']);
case 404: //Resource Not Found
throw NotFoundException(response.body);
throw NotFoundException(jsonDecode(response.body)['message']);
case 500: //Internal Server Error
default:
throw FetchDataException(
Expand Down
7 changes: 1 addition & 6 deletions lib/Data/Repository/home_page_repo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,8 @@ abstract class DemoRepository {
class DemoRepo extends DemoRepository {
@override
Future<DemoModel> fetchData() async {
try{
final response =
final response =
await BaseClient().get('${(dotenv.env['API_BASE_URL'])}/todos/1');
return DemoModel.fromJson(response);
}
catch(e){
throw e.toString();
}
}
}
27 changes: 27 additions & 0 deletions lib/Presentation/Components/future_builder.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import 'package:flutter/material.dart';

class FutureBuilderWidget extends StatelessWidget {
const FutureBuilderWidget({Key? key, required this.futureCall})
: super(key: key);

final Future futureCall;

@override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureCall,
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.toString());
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else if (snapshot.connectionState == ConnectionState.waiting) {
return const Text('Waiting....');
} else if (snapshot.connectionState == ConnectionState.none) {
return const Text('cannot establish connection with the server.');
}
return const Center(child: CircularProgressIndicator());
},
);
}
}
19 changes: 4 additions & 15 deletions lib/Presentation/Screens/HomePage/UI/home_page.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:api_exceptions_part2/Data/Repository/home_page_repo.dart';
import '../../../../Data/Repository/home_page_repo.dart';
import '../../../Components/future_builder.dart';
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
Expand All @@ -18,20 +19,8 @@ class _MyHomePageState extends State<MyHomePage> {
title: Text(widget.title),
),
body: Center(
child: ElevatedButton(
onPressed: () => getData(),
child: const Text('Fetch Data'),
)),
child: FutureBuilderWidget(futureCall: DemoRepo().fetchData()),
),
);
}

Future<void> getData() async {
print('getting data');
try {
var response = await DemoRepo().fetchData();
print(response);
} catch (e) {
print(e.toString());
}
}
}