无法在飞镖中捕获异常

时间:2020-04-07 15:00:29

标签: node.js flutter dart try-catch

我正在尝试对已经存在且无效的电子邮件进行验证。我从api收到响应:无效电子邮件的INVALID_EMAIL和已注册用户的EMAIL_EXISTS。

在auth_screen.dart中,我正在获取输入并将其从那里调用api发送到auth.dart提供程序,并获得响应并抛出错误并尝试在auth_screen.dart中解决它。

但是我无法捕捉到错误并在此处的对话框中显示


    } on HttpException catch(error){
      var errorMessage = 'Authentication failed';
      if (error.toString().contains('EMAIL_EXISTS')){
        errorMessage = 'E-mail address already exists!';
      } else 
      if (error.toString().contains('INVALID_EMAIL')){
        errorMessage = 'This is not a valid email address';
      }
    }


http_exception.dart

    class HttpException implements Exception {
       final String message;
       HttpException(this.message)
       @override
       String toString() {
          return message;
          // return super.toString(); // Instance of HttpException
       }
    }

    auth_screen.dart

    try{
        if (_authMode == AuthMode.Login) {
        // Log user in
            Provider.of<Auth>(context, listen: false).login(_authData['email'], _authData['password']);
        } else {
        // Sign up
            Provider.of<Auth>(context, listen: false).signup(_authData['email'], _authData['password']);
        }
    } on HttpException catch(error){
        var errorMessage = 'Authentication failed';
        if (error.toString().contains('EMAIL_EXISTS')){
            errorMessage = 'E-mail address already exists!';
        } else if (error.toString().contains('INVALID_EMAIL')){
             errorMessage = 'This is not a valid email address';
        }
    _showErrorDialog(errorMessage);


auth.dart

    Future<void> signup(String email, String password) async {
      const url = 'http://10.0.2.2:8080/auth/signup';
      try {
        final response = await http.put(
        url,
        headers: {"Content-Type": "application/json"},
        body: json.encode(
          {
            'email': email,
            'password': password,
          },
        ),
      );

      final responseData = json.decode(response.body);
      print(responseData);
      if(responseData['error'] != null){
        throw HttpException(responseData['errmsg']);
      } catch(error){
        throw error;
      }
    }

0 个答案:

没有答案