2
0
mirror of https://github.com/inventree/inventree-app.git synced 2025-04-28 13:36:50 +00:00

Pass URL through to the showServeError method

- Can decide, based on the URL, if we want to show an error
This commit is contained in:
Oliver Walters 2022-06-03 20:23:59 +10:00
parent 99462ffeb9
commit dbc024491c
5 changed files with 74 additions and 120 deletions

View File

@ -341,7 +341,7 @@ class InvenTreeAPI {
response = await get("", expectedStatusCode: 200); response = await get("", expectedStatusCode: 200);
if (!response.successful()) { if (!response.successful()) {
showStatusCodeError(response.statusCode); showStatusCodeError(apiUrl, response.statusCode);
return false; return false;
} }
@ -351,6 +351,7 @@ class InvenTreeAPI {
if (!data.containsKey("server") || !data.containsKey("version") || !data.containsKey("instance")) { if (!data.containsKey("server") || !data.containsKey("version") || !data.containsKey("instance")) {
showServerError( showServerError(
apiUrl,
L10().missingData, L10().missingData,
L10().serverMissingData, L10().serverMissingData,
); );
@ -378,6 +379,7 @@ class InvenTreeAPI {
message += "Ensure your InvenTree server version is up to date!"; message += "Ensure your InvenTree server version is up to date!";
showServerError( showServerError(
apiUrl,
L10().serverOld, L10().serverOld,
message, message,
); );
@ -401,12 +403,13 @@ class InvenTreeAPI {
case 401: case 401:
case 403: case 403:
showServerError( showServerError(
apiUrl,
L10().serverAuthenticationError, L10().serverAuthenticationError,
L10().invalidUsernamePassword, L10().invalidUsernamePassword,
); );
break; break;
default: default:
showStatusCodeError(response.statusCode); showStatusCodeError(apiUrl, response.statusCode);
break; break;
} }
@ -417,6 +420,7 @@ class InvenTreeAPI {
if (!data.containsKey("token")) { if (!data.containsKey("token")) {
showServerError( showServerError(
apiUrl,
L10().tokenMissing, L10().tokenMissing,
L10().tokenMissingFromResponse, L10().tokenMissingFromResponse,
); );
@ -631,12 +635,12 @@ class InvenTreeAPI {
Uri? _uri = Uri.tryParse(makeUrl(url)); Uri? _uri = Uri.tryParse(makeUrl(url));
if (_uri == null) { if (_uri == null) {
showServerError(L10().invalidHost, L10().invalidHostDetails); showServerError(url, L10().invalidHost, L10().invalidHostDetails);
return; return;
} }
if (_uri.host.isEmpty) { if (_uri.host.isEmpty) {
showServerError(L10().invalidHost, L10().invalidHostDetails); showServerError(url, L10().invalidHost, L10().invalidHostDetails);
return; return;
} }
@ -644,7 +648,7 @@ class InvenTreeAPI {
final bool strictHttps = await InvenTreeSettingsManager().getValue(INV_STRICT_HTTPS, false) as bool; final bool strictHttps = await InvenTreeSettingsManager().getValue(INV_STRICT_HTTPS, false) as bool;
var client = createClient(strictHttps: strictHttps); var client = createClient(url, strictHttps: strictHttps);
// Attempt to open a connection to the server // Attempt to open a connection to the server
try { try {
@ -658,20 +662,20 @@ class InvenTreeAPI {
} on SocketException catch (error) { } on SocketException catch (error) {
debug("SocketException at ${url}: ${error.toString()}"); debug("SocketException at ${url}: ${error.toString()}");
showServerError(L10().connectionRefused, error.toString()); showServerError(url, L10().connectionRefused, error.toString());
return; return;
} on TimeoutException { } on TimeoutException {
print("TimeoutException at ${url}"); print("TimeoutException at ${url}");
showTimeoutError(); showTimeoutError(url);
return; return;
} on HandshakeException catch (error) { } on HandshakeException catch (error) {
print("HandshakeException at ${url}:"); print("HandshakeException at ${url}:");
debug(error.toString()); debug(error.toString());
showServerError(L10().serverCertificateError, error.toString()); showServerError(url, L10().serverCertificateError, error.toString());
return; return;
} catch (error, stackTrace) { } catch (error, stackTrace) {
print("Server error at ${url}: ${error.toString()}"); print("Server error at ${url}: ${error.toString()}");
showServerError(L10().serverError, error.toString()); showServerError(url, L10().serverError, error.toString());
sentryReportError( sentryReportError(
"api.downloadFile : client.openUrl", "api.downloadFile : client.openUrl",
error, stackTrace, error, stackTrace,
@ -693,16 +697,16 @@ class InvenTreeAPI {
OpenFile.open(local_path); OpenFile.open(local_path);
} }
} else { } else {
showStatusCodeError(response.statusCode); showStatusCodeError(url, response.statusCode);
} }
} on SocketException catch (error) { } on SocketException catch (error) {
showServerError(L10().connectionRefused, error.toString()); showServerError(url, L10().connectionRefused, error.toString());
} on TimeoutException { } on TimeoutException {
showTimeoutError(); showTimeoutError(url);
} catch (error, stackTrace) { } catch (error, stackTrace) {
print("Error downloading image:"); print("Error downloading image:");
print(error.toString()); print(error.toString());
showServerError(L10().downloadError, error.toString()); showServerError(url, L10().downloadError, error.toString());
sentryReportError( sentryReportError(
"api.downloadFile : client.closeRequest", "api.downloadFile : client.closeRequest",
error, stackTrace, error, stackTrace,
@ -767,11 +771,12 @@ class InvenTreeAPI {
); );
} }
} on SocketException catch (error) { } on SocketException catch (error) {
showServerError(L10().connectionRefused, error.toString()); showServerError(url, L10().connectionRefused, error.toString());
response.error = "SocketException"; response.error = "SocketException";
response.errorDetail = error.toString(); response.errorDetail = error.toString();
} on FormatException { } on FormatException {
showServerError( showServerError(
url,
L10().formatException, L10().formatException,
L10().formatExceptionJson + ":\n${jsondata}" L10().formatExceptionJson + ":\n${jsondata}"
); );
@ -786,10 +791,10 @@ class InvenTreeAPI {
); );
} on TimeoutException { } on TimeoutException {
showTimeoutError(); showTimeoutError(url);
response.error = "TimeoutException"; response.error = "TimeoutException";
} catch (error, stackTrace) { } catch (error, stackTrace) {
showServerError(L10().serverError, error.toString()); showServerError(url, L10().serverError, error.toString());
sentryReportError( sentryReportError(
"api.uploadFile", "api.uploadFile",
error, stackTrace error, stackTrace
@ -845,7 +850,7 @@ class InvenTreeAPI {
); );
} }
HttpClient createClient({bool strictHttps = false}) { HttpClient createClient(String url, {bool strictHttps = false}) {
var client = HttpClient(); var client = HttpClient();
@ -853,6 +858,7 @@ class InvenTreeAPI {
if (strictHttps) { if (strictHttps) {
showServerError( showServerError(
url,
L10().serverCertificateError, L10().serverCertificateError,
L10().serverCertificateInvalid, L10().serverCertificateInvalid,
); );
@ -897,12 +903,12 @@ class InvenTreeAPI {
Uri? _uri = Uri.tryParse(_url); Uri? _uri = Uri.tryParse(_url);
if (_uri == null) { if (_uri == null) {
showServerError(L10().invalidHost, L10().invalidHostDetails); showServerError(url, L10().invalidHost, L10().invalidHostDetails);
return null; return null;
} }
if (_uri.host.isEmpty) { if (_uri.host.isEmpty) {
showServerError(L10().invalidHost, L10().invalidHostDetails); showServerError(url, L10().invalidHost, L10().invalidHostDetails);
return null; return null;
} }
@ -910,7 +916,7 @@ class InvenTreeAPI {
final bool strictHttps = await InvenTreeSettingsManager().getValue(INV_STRICT_HTTPS, false) as bool; final bool strictHttps = await InvenTreeSettingsManager().getValue(INV_STRICT_HTTPS, false) as bool;
var client = createClient(strictHttps: strictHttps); var client = createClient(url, strictHttps: strictHttps);
// Attempt to open a connection to the server // Attempt to open a connection to the server
try { try {
@ -925,25 +931,25 @@ class InvenTreeAPI {
return _request; return _request;
} on SocketException catch (error) { } on SocketException catch (error) {
print("SocketException at ${url}: ${error.toString()}"); print("SocketException at ${url}: ${error.toString()}");
showServerError(L10().connectionRefused, error.toString()); showServerError(url, L10().connectionRefused, error.toString());
return null; return null;
} on TimeoutException { } on TimeoutException {
print("TimeoutException at ${url}"); print("TimeoutException at ${url}");
showTimeoutError(); showTimeoutError(url);
return null; return null;
} on CertificateException catch (error) { } on CertificateException catch (error) {
print("CertificateException at ${url}:"); print("CertificateException at ${url}:");
print(error.toString()); print(error.toString());
showServerError(L10().serverCertificateError, error.toString()); showServerError(url, L10().serverCertificateError, error.toString());
return null; return null;
} on HandshakeException catch (error) { } on HandshakeException catch (error) {
print("HandshakeException at ${url}:"); print("HandshakeException at ${url}:");
print(error.toString()); print(error.toString());
showServerError(L10().serverCertificateError, error.toString()); showServerError(url, L10().serverCertificateError, error.toString());
return null; return null;
} catch (error, stackTrace) { } catch (error, stackTrace) {
print("Server error at ${url}: ${error.toString()}"); print("Server error at ${url}: ${error.toString()}");
showServerError(L10().serverError, error.toString()); showServerError(url, L10().serverError, error.toString());
sentryReportError( sentryReportError(
"api.apiRequest : openUrl", "api.apiRequest : openUrl",
error, stackTrace, error, stackTrace,
@ -975,6 +981,8 @@ class InvenTreeAPI {
url: request.uri.toString() url: request.uri.toString()
); );
String url = request.uri.toString();
try { try {
HttpClientResponse? _response = await request.close().timeout(Duration(seconds: 10)); HttpClientResponse? _response = await request.close().timeout(Duration(seconds: 10));
@ -982,7 +990,7 @@ class InvenTreeAPI {
// If the server returns a server error code, alert the user // If the server returns a server error code, alert the user
if (_response.statusCode >= 500) { if (_response.statusCode >= 500) {
showStatusCodeError(_response.statusCode); showStatusCodeError(url, _response.statusCode);
sentryReportMessage( sentryReportMessage(
"Server error", "Server error",
@ -1001,31 +1009,31 @@ class InvenTreeAPI {
if (ignoreResponse) { if (ignoreResponse) {
response.data = {}; response.data = {};
} else { } else {
response.data = await responseToJson(_response) ?? {}; response.data = await responseToJson(url, _response) ?? {};
} }
if (statusCode != null) { if (statusCode != null) {
// Expected status code not returned // Expected status code not returned
if (statusCode != _response.statusCode) { if (statusCode != _response.statusCode) {
showStatusCodeError(_response.statusCode); showStatusCodeError(url, _response.statusCode);
} }
} }
} }
} on SocketException catch (error) { } on SocketException catch (error) {
showServerError(L10().connectionRefused, error.toString()); showServerError(url, L10().connectionRefused, error.toString());
response.error = "SocketException"; response.error = "SocketException";
response.errorDetail = error.toString(); response.errorDetail = error.toString();
} on CertificateException catch (error) { } on CertificateException catch (error) {
print("CertificateException at ${request.uri.toString()}:"); print("CertificateException at ${request.uri.toString()}:");
print(error.toString()); print(error.toString());
showServerError(L10().serverCertificateError, error.toString()); showServerError(url, L10().serverCertificateError, error.toString());
} on TimeoutException { } on TimeoutException {
showTimeoutError(); showTimeoutError(url);
response.error = "TimeoutException"; response.error = "TimeoutException";
} catch (error, stackTrace) { } catch (error, stackTrace) {
showServerError(L10().serverError, error.toString()); showServerError(url, L10().serverError, error.toString());
sentryReportError("api.completeRequest", error, stackTrace); sentryReportError("api.completeRequest", error, stackTrace);
response.error = "UnknownError"; response.error = "UnknownError";
response.errorDetail = error.toString(); response.errorDetail = error.toString();
@ -1038,7 +1046,7 @@ class InvenTreeAPI {
/* /*
* Convert a HttpClientResponse response object to JSON * Convert a HttpClientResponse response object to JSON
*/ */
dynamic responseToJson(HttpClientResponse response) async { dynamic responseToJson(String url, HttpClientResponse response) async {
String body = await response.transform(utf8.decoder).join(); String body = await response.transform(utf8.decoder).join();
@ -1058,6 +1066,7 @@ class InvenTreeAPI {
); );
showServerError( showServerError(
url,
L10().formatException, L10().formatException,
L10().formatExceptionJson + ":\n${body}" L10().formatExceptionJson + ":\n${body}"
); );

View File

@ -1288,7 +1288,7 @@ class _APIFormWidgetState extends State<APIFormWidget> {
final response = await _submit(data); final response = await _submit(data);
if (!response.isValid()) { if (!response.isValid()) {
showServerError(L10().serverError, L10().responseInvalid); showServerError(url, L10().serverError, L10().responseInvalid);
return; return;
} }

View File

@ -81,7 +81,7 @@ class BarcodeHandler {
barcodeFailureTone(); barcodeFailureTone();
// Called when the server returns an unhandled response // Called when the server returns an unhandled response
showServerError(L10().responseUnknown, data.toString()); showServerError("barcode/", L10().responseUnknown, data.toString());
_controller?.resumeCamera(); _controller?.resumeCamera();
} }
@ -440,6 +440,7 @@ class UniqueBarcodeHandler extends BarcodeHandler {
if (!data.containsKey("hash")) { if (!data.containsKey("hash")) {
showServerError( showServerError(
"barcode/",
L10().missingData, L10().missingData,
L10().barcodeMissingHash, L10().barcodeMissingHash,
); );

View File

@ -270,6 +270,7 @@ class InvenTreeModel {
); );
showServerError( showServerError(
url,
L10().serverError, L10().serverError,
L10().errorDelete, L10().errorDelete,
); );
@ -299,6 +300,7 @@ class InvenTreeModel {
); );
showServerError( showServerError(
url,
L10().serverError, L10().serverError,
L10().errorFetch, L10().errorFetch,
); );
@ -367,6 +369,7 @@ class InvenTreeModel {
); );
showServerError( showServerError(
url,
L10().serverError, L10().serverError,
L10().errorFetch, L10().errorFetch,
); );
@ -408,6 +411,7 @@ class InvenTreeModel {
); );
showServerError( showServerError(
URL,
L10().serverError, L10().serverError,
L10().errorCreate, L10().errorCreate,
); );

View File

@ -7,6 +7,7 @@ import "package:inventree/l10.dart";
import "package:inventree/preferences.dart"; import "package:inventree/preferences.dart";
import "package:inventree/widget/snacks.dart"; import "package:inventree/widget/snacks.dart";
Future<void> confirmationDialog(String title, String text, {IconData icon = FontAwesomeIcons.questionCircle, String? acceptText, String? rejectText, Function? onAccept, Function? onReject}) async { Future<void> confirmationDialog(String title, String text, {IconData icon = FontAwesomeIcons.questionCircle, String? acceptText, String? rejectText, Function? onAccept, Function? onReject}) async {
String _accept = acceptText ?? L10().ok; String _accept = acceptText ?? L10().ok;
@ -50,30 +51,6 @@ Future<void> confirmationDialog(String title, String text, {IconData icon = Font
} }
Future<void> showInfoDialog(String title, String description, {IconData icon = FontAwesomeIcons.info, String? info, Function()? onDismissed}) async {
String _info = info ?? L10().info;
OneContext().showDialog(
builder: (BuildContext context) => SimpleDialog(
title: ListTile(
title: Text(_info),
leading: FaIcon(icon),
),
children: <Widget>[
ListTile(
title: Text(title),
subtitle: Text(description)
)
]
)
).then((value) {
if (onDismissed != null) {
onDismissed();
}
});
}
Future<void> showErrorDialog(String title, String description, {IconData icon = FontAwesomeIcons.exclamationCircle, String? error, Function? onDismissed}) async { Future<void> showErrorDialog(String title, String description, {IconData icon = FontAwesomeIcons.exclamationCircle, String? error, Function? onDismissed}) async {
String _error = error ?? L10().error; String _error = error ?? L10().error;
@ -98,7 +75,19 @@ Future<void> showErrorDialog(String title, String description, {IconData icon =
}); });
} }
Future<void> showServerError(String title, String description) async { /*
* Display a message indicating the nature of a server / API error
*/
Future<void> showServerError(String url, String title, String description) async {
if (!OneContext.hasContext) {
return;
}
// We ignore error messages for certain URLs
if (url.contains("notifications")) {
return;
}
if (title.isEmpty) { if (title.isEmpty) {
title = L10().serverError; title = L10().serverError;
@ -126,7 +115,10 @@ Future<void> showServerError(String title, String description) async {
); );
} }
Future<void> showStatusCodeError(int status) async { /*
* Displays an error indicating that the server returned an unexpected status code
*/
Future<void> showStatusCodeError(String url, int status) async {
String msg = L10().responseInvalid; String msg = L10().responseInvalid;
String extra = "${L10().statusCode}: ${status}"; String extra = "${L10().statusCode}: ${status}";
@ -173,68 +165,16 @@ Future<void> showStatusCodeError(int status) async {
} }
showServerError( showServerError(
url,
msg, msg,
extra, extra,
); );
} }
Future<void> showTimeoutError() async {
await showServerError(L10().timeout, L10().noResponse); /*
} * Displays a message indicating that the server timed out on a certain request
*/
void showFormDialog(String title, {String? acceptText, String? cancelText, GlobalKey<FormState>? key, List<Widget>? fields, Function? callback}) { Future<void> showTimeoutError(String url) async {
await showServerError(url, L10().timeout, L10().noResponse);
String _accept = acceptText ?? L10().save;
String _cancel = cancelText ?? L10().cancel;
List<Widget> _fields = fields ?? [];
OneContext().showDialog(
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
actions: <Widget>[
TextButton(
child: Text(_cancel),
onPressed: () {
// Close the form
Navigator.pop(context);
}
),
TextButton(
child: Text(_accept),
onPressed: () {
var _key = key;
if (_key != null && _key.currentState != null) {
if (_key.currentState!.validate()) {
_key.currentState!.save();
Navigator.pop(context);
// Callback
if (callback != null) {
callback();
}
}
}
}
)
],
content: Form(
key: key,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: _fields
)
)
)
);
}
);
} }