aws-amplify / amplify-flutter

A declarative library with an easy-to-use interface for building Flutter applications on AWS.
https://docs.amplify.aws
Apache License 2.0
1.31k stars 245 forks source link

flutter: Error uploading file: StorageException(message: Unexpected error occurred with message: An unknown error occurred, recoverySuggestion: This should not happen. #1294

Closed patelnirav48 closed 2 years ago

patelnirav48 commented 2 years ago

Describe the bug

// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 //

import Foundation

/// Amplify error raised in the Auth category. public enum AuthError {

/// Caused by issue in the way auth category is configured
case configuration(ErrorDescription, RecoverySuggestion, Error? = nil)

/// Caused by some error in the underlying service. Check the associated error for more details.
case service(ErrorDescription, RecoverySuggestion, Error? = nil)

/// Caused by an unknown reason
case unknown(ErrorDescription, Error? = nil)

/// Caused when one of the input field is invalid
case validation(Field, ErrorDescription, RecoverySuggestion, Error? = nil)

/// Caused when the current session is not authorized to perform an operation
case notAuthorized(ErrorDescription, RecoverySuggestion, Error? = nil)

/// Caused when an operation is not valid with the current state of Auth category
case invalidState(ErrorDescription, RecoverySuggestion, Error? = nil)

/// Caused when an operation needs the user to be in signedIn state
case signedOut(ErrorDescription, RecoverySuggestion, Error? = nil)

/// Caused when a session is expired and needs the user to be re-authenticated
case sessionExpired(ErrorDescription, RecoverySuggestion, Error? = nil)

}

extension AuthError: AmplifyError {

public var underlyingError: Error? {
    switch self {
    case .configuration(_, _, let underlyingError),
         .service(_, _, let underlyingError),
         .unknown(_, let underlyingError),
         .validation(_, _, _, let underlyingError),
         .notAuthorized(_, _, let underlyingError),
         .sessionExpired(_, _, let underlyingError),
         .signedOut(_, _, let underlyingError),
         .invalidState(_, _, let underlyingError):
        return underlyingError
    }
}

public var errorDescription: ErrorDescription {
    switch self {
    case .configuration(let errorDescription, _, _),
         .service(let errorDescription, _, _),
         .validation(_, let errorDescription, _, _),
         .notAuthorized(let errorDescription, _, _),
         .signedOut(let errorDescription, _, _),
         .sessionExpired(let errorDescription, _, _),
         .invalidState(let errorDescription, _, _):
        return errorDescription
    case .unknown(let errorDescription, _):
        return "Unexpected error occurred with message: \(errorDescription)"
    }
}

public var recoverySuggestion: RecoverySuggestion {
    switch self {
    case .configuration(_, let recoverySuggestion, _),
         .service(_, let recoverySuggestion, _),
         .validation(_, _, let recoverySuggestion, _),
         .notAuthorized(_, let recoverySuggestion, _),
         .signedOut(_, let recoverySuggestion, _),
         .sessionExpired(_, let recoverySuggestion, _),
         .invalidState(_, let recoverySuggestion, _):
        return recoverySuggestion
    case .unknown:
        return AmplifyErrorMessages.shouldNotHappenReportBugToAWS()
    }
}

public init(
    errorDescription: ErrorDescription = "An unknown error occurred",
    recoverySuggestion: RecoverySuggestion = "(Ignored)",
    error: Error
) {
    if let error = error as? Self {
        self = error
    } else if error.isOperationCancelledError {
        self = .unknown("Operation cancelled", error)
    } else {
        self = .unknown(errorDescription, error)
    }
}

}

Steps To Reproduce

When i try to upload image using Amplify.Storage.uploadFile, its through exception.

Expected behavior

Should allow to upload image to aws s3

Amplify Framework Version

0.2.10

Amplify Categories

Storage

Dependency manager

Cocoapods

Swift version

5.0

CLI version

7.6.7

Xcode version

13.1

Relevant log output

No response

Is this a regression?

No

Regression additional context

No response

Device

iPhone 8 Plus

iOS Version

iOS 15

Specific to simulators

No response

Additional context

No response

ameter commented 2 years ago

Hi, can you provide some more information to help us identify the issue? Specifically, if you can provide a sample of the code you're running that will reproduce the issue and your configuration with any sensitive information removed that would be helpful.

patelnirav48 commented 2 years ago

1) Using below method to configure amplify

void _initAmplifyFlutter() async {
    AmplifyAuthCognito auth = AmplifyAuthCognito();
    AmplifyStorageS3 storage = AmplifyStorageS3();

    Amplify.addPlugins([auth, storage]);

    //Initialize AmplifyFlutter
    try {
      await Amplify.configure(amplifyconfig);

      print("Amplify was configured.");
    } on AmplifyAlreadyConfiguredException {
      print("Amplify was already configured. Looks like app restarted on android.");
    }
  }

2) Below code to upload to storage

  FilePickerResult? pickResult =
    await FilePicker.platform.pickFiles(type: FileType.image);
    if (pickResult == null) {
      print('User canceled upload.');
      return;
    }
    File file = File(pickResult.files.single.path!);

    // Upload image with the current time as the key
    final key = new DateTime.now().toString();
    Map<String, String> metadata = <String, String>{};
    metadata['name'] = 'filename';
    metadata['desc'] = 'A test file';
    S3UploadFileOptions options = S3UploadFileOptions(
        accessLevel: StorageAccessLevel.guest, metadata: metadata);

    // Upload the file to S3 with options
    try {
      final UploadFileResult result = await Amplify.Storage.uploadFile(
          local: file,
          key: key,
          options: options,
          onProgress: (progress) {
            print("Fraction completed: " + progress.getFractionCompleted().toString());
          }
      );
      print('Successfully uploaded file: ${result.key}');
    } on StorageException catch (e) {
      print('Error uploading file: $e');
    }

3) amplifyconfiguration.dart file, when i did amplify init command its contain only UserAgent, version

    const amplifyconfig = ''' {
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "auth": {
        "plugins": {
            "awsCognitoAuthPlugin": {
                "UserAgent": "aws-amplify-cli/0.1.0",
                "Version": "0.1.0",
                "IdentityManager": {
                    "Default": {}
                },
                "CredentialsProvider": {
                    "CognitoIdentity": {
                        "Default": {
                            "PoolId": "us-east-1:*********",
                            "Region": "us-east-1"
                        }
                    }
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "us-east-1_*********",
                        "AppClientId": "*********",
                        "AppClientSecret": "*********",
                        "Region": "us-east-1"
                    }
                },
                "Auth": {
                    "Default": {
                        "authenticationFlowType": "USER_SRP_AUTH"
                    }
                },
                "S3TransferUtility": {
                    "Default": {
                        "Bucket": "qa-*********-bucket",
                        "Region": "us-east-1"
                    }

                }
            }
        }
    },
    "storage": {
        "plugins": {
            "awsS3StoragePlugin": {
                "bucket": "qa-*********-bucket",
                "region": "us-east-1",
                "defaultAccessLevel": "guest"
            }
        }
    }
}''';
Jordan-Nelson commented 2 years ago

@patelnirav48 - What version of Amplify-Flutter are you using? Can you give an output of running flutter pub deps --no-dev --style=compact in your project?

offlineprogrammer commented 2 years ago

Hi @patelnirav48

I am closing this issue for now as we didn't hear from you We can reopen it if you are still facing the issue and when you provide the details

Regards Mo