Hello,
I'm working on a user registration page for the web and could use some help with error handling. I have a registration page that presents a form and then calls the addUser() function to send an http post to my api server, which in turn sends the sql insert to the database. It works fine when there are no errors and I present a 'success' page. What I'm trying to do is present an alert window when an error occurs that notifies the user that the registration was not successful and support has been notified. At that point, I send an email containing the error and the user's email to my support inbox so I can notify them when the problem is resolved. The trouble I am having is I can't seem to isolate the success code from the error code. When I test the code below by ending the api server or database server, I always hit the if statement that tests the response code and it is of course null because the post failed before it could return with a valid response. (Error message:
TypeError: Cannot read property 'statusCode' of null)
I was expecting the if block to be skipped when an error occured with the post and the catch block would be executed, but evidently it doesn't quit work that way. Is there another way to have the if block not execute if there is an error? I must be missing something obvious.
Thanks for any help or suggestions.
Kevin
Future addUser() async {
http.Response response;
...
try {
Constants.API_URL + '/addUser',
headers: <String, String>{'Content-Type': 'application/json'},
body: json.encode(regForm),
);
if (response.statusCode == 200) {
Navigator.of(context).pushNamed(Success.route);
}
} catch (e) {
String subject = Messages.ERROR_USER_REGISTRATION_FAILED;
String error =
'Error registering user $user. Error: e.toString()';
errorMsg(context, user, subject, error);
}
}
}