본문 바로가기
개발/Flutter

custom exception

by dev_caleb 2022. 11. 14.
728x90

 

 

https://stackoverflow.com/questions/13579982/how-to-create-a-custom-exception-and-handle-it-in-dart

 

How to create a custom exception and handle it in dart

I have written this code to test how custom exceptions are working in the dart. I'm not getting the desired output could someone explain to me how to handle it?? void main() { try {

stackoverflow.com

 

다음과 같이 쓸 수 있다! CustomException은 일단 util 쪽에 넣어뒀는데 더 적당한 곳이 보이면 옮기려고 한다.!

 

class CustomException implements Exception {
  String cause;
  CustomException(this.cause);
}

 

void requestAuth() async {
  final mobisService = Get.find<MobisService>();

  loading.value = true;

  try {
    bool isOk = false;

    if (emailAuth.value) {
      final email = emailInput.text.trim();
      if (email.isEmpty) throw CustomException('no_email');
      if (!email.isEmail) throw CustomException('email_format');

      isOk = await mobisService.sendValidationEmail(email);
    } else {
      final mobile = mobileInput.text.trim();
      if (mobile.isEmpty) throw CustomException('no_mobile');
      if (!mobile.isNumericOnly) throw CustomException('mobile_format');

      isOk = await mobisService.sendValidationSms(mobile);
    }

    if (!isOk) throw CustomException('server_error');

    showToastMessage('인증번호가 발송되었습니다.');
    changeStep(3);
  } on CustomException catch (e) {
    switch (e.cause) {
      case 'no_email':
        showToastMessage('이메일 주소를 입력해 주세요.');
        break;
      case 'email_format':
        showToastMessage('이메일 형식을 확인해 주세요.');
        break;
      case 'no_mobile':
        showToastMessage('휴대폰 번호를 입력해 주세요.');
        break;
      case 'mobile_format':
        showToastMessage('휴대폰 번호 형식을 확인해 주세요.');
        break;
      default:
        showToastMessage('인증번호가 발송되지 않았습니다.');
    }
  } finally {
    loading.value = false;
  }
}

 

728x90