【问题标题】:Unhandled exception issue after throwing my custom exception class抛出我的自定义异常类后未处理的异常问题
【发布时间】:2021-12-30 14:10:40
【问题描述】:

我正在抛出我的 HttpException,但它没有达到 on HttpException catch,老实说,我不知道有什么问题。

这是我的自定义 HttpException 类:

class HttpException implements Exception {
  final String message;

  HttpException(this.message);

  @override
  String toString() {
    return message;
    // return super.toString(); // Instance of HttpException
  }
}

这是我的 try catch 块:

这个在登录和注册方法中的提供者中:

try{
      final response = await http.post(url, body: json.encode({
        'email': email,
        'password': password,
        'returnSecureToken': true
      }));
      final responseData = json.decode(response.body);
      if (responseData['error'] != null) {
        throw HttpException(responseData['error']['message']);
      }
    } catch (error) {
      return Future.error(error);
    }
  }

在这里我想捕捉我的 HttpException 但我的代码没有达到这个。

try{
      if (_authMode == AuthMode.Login) {
        // Log user in
        await Provider.of<Auth>(context, listen: false).login(_authData['email'], _authData['password']);
      } else {
        // Sign user up
        await 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 = 'This email address is already in use';
      } else if(error.toString().contains('INVALID_EMAIL')) {
        errorMessage = 'Its not a valid email';
      } else if(error.toString().contains('WEAK_PASSWORD')){
        errorMessage = 'This password is too weak';
      } else if(error.toString().contains('EMAIL_NOT_FOUND')){
        errorMessage = 'Could not find that email';
      } else if(error.toString().contains('INVALID_PASSWORD')){
        errorMessage = 'Invalid password';
      }
      _showErrorDialog(errorMessage);
    } catch (error) {
      var errorMessage = 'Could not authenticate you, please try again later';
      _showErrorDialog(errorMessage);
    }

我在调试器中检查了这一点,我的错误消息是例如:'EMAIL_EXISTS',但我在控制台中有这个错误而不是对话框: Unhandled Exception: EMAIL_EXISTS

【问题讨论】:

  • 您确定返回您的Future 的代码是正确的awaited?
  • 是的,我现在检查了一下,它看起来正常

标签: flutter try-catch


【解决方案1】:

代替

return Future.error(HttpException(responseData['error']['message']));

试试

throw HttpException(responseData['error']['message']);

将 return 替换为 throw,因为 Exceptions 需要为 thrownFuture.error().catchError() 捕获

【讨论】:

  • 我之前有过这个,它仍然是相同的行为
  • 你的输出到底是什么?
  • [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: EMAIL_NOT_FOUND
猜你喜欢
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 2016-04-18
  • 2019-07-15
  • 2013-07-24
  • 1970-01-01
  • 2022-12-07
  • 2011-05-30
相关资源
最近更新 更多