simplified code across the app and consolidated duplicated helpers
This commit is contained in:
@@ -3,6 +3,7 @@ import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import 'errors/app_exception.dart';
|
||||
import 'errors/auth_exception.dart';
|
||||
import 'errors/network_exception.dart';
|
||||
import 'errors/not_found_exception.dart';
|
||||
@@ -42,12 +43,23 @@ String httpErrorDetail(String label, String body, int status) {
|
||||
: '$label -> HTTP $status body=$preview';
|
||||
}
|
||||
|
||||
/// Throws the [AppException] matching a non-2xx HTTP [status], carrying
|
||||
/// [detail] as technical details: 401/403 map to auth errors, 404 to
|
||||
/// not-found, everything else to a generic server error.
|
||||
Never throwForStatus(int status, String detail) {
|
||||
if (status == 401) throw AuthException.unauthorized(technicalDetails: detail);
|
||||
if (status == 403) throw AuthException.forbidden(technicalDetails: detail);
|
||||
if (status == 404) throw NotFoundException(technicalDetails: detail);
|
||||
throw ServerException(statusCode: status, technicalDetails: detail);
|
||||
/// The [AppException] matching a non-2xx HTTP [status], carrying [detail] as
|
||||
/// technical details: 401/403 map to auth errors, 404 to not-found, everything
|
||||
/// else to a generic server error.
|
||||
AppException exceptionForStatus(int status, String detail) => switch (status) {
|
||||
401 => AuthException.unauthorized(technicalDetails: detail),
|
||||
403 => AuthException.forbidden(technicalDetails: detail),
|
||||
404 => NotFoundException(technicalDetails: detail),
|
||||
_ => ServerException(statusCode: status, technicalDetails: detail),
|
||||
};
|
||||
|
||||
/// Throws [exceptionForStatus].
|
||||
Never throwForStatus(int status, String detail) =>
|
||||
throw exceptionForStatus(status, detail);
|
||||
|
||||
/// Throws [exceptionForStatus] unless [response] is 2xx.
|
||||
void ensureSuccess(String label, http.Response response) {
|
||||
final status = response.statusCode;
|
||||
if (status >= 200 && status < 300) return;
|
||||
throwForStatus(status, httpErrorDetail(label, response.body, status));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user