Errors
class Errors
Create exceptions for common error cases.
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography;
namespace Azure.Storage
{
internal class Errors
{
public static class ClientSideEncryption
{
public static ArgumentException UnrecognizedVersion()
{
return new ArgumentException("Unrecognized ClientSideEncryptionVersion");
}
public static InvalidOperationException ClientSideEncryptionVersionNotSupported(string versionString = null)
{
return new InvalidOperationException(("This library does not support the given version of client-side encryption." + versionString == null) ? "" : (" Version ID = " + versionString));
}
public static InvalidOperationException TypeNotSupported(Type type)
{
return new InvalidOperationException("Client-side encryption is not supported for type \"" + type.FullName + "\". Please use a supported client type or create this client without specifying client-side encryption options.");
}
public static InvalidOperationException MissingRequiredEncryptionResources(params string[] resourceNames)
{
return new InvalidOperationException("Cannot encrypt without specifying " + string.Join(",", resourceNames.AsEnumerable()));
}
public static ArgumentException KeyNotFound(string keyId)
{
return new ArgumentException("Resolution of id " + keyId + " returned null.");
}
public static ArgumentException BadEncryptionAgent(string agent)
{
return new ArgumentException("Invalid Encryption Agent. This version of the client library does not understandthe Encryption Agent protocol \"" + agent + "\" set on the blob.");
}
public static ArgumentException BadEncryptionAlgorithm(string algorithm)
{
return new ArgumentException("Invalid Encryption Algorithm \"" + algorithm + "\" found on the resource. This version of the clientlibrary does not support the given encryption algorithm.");
}
public static InvalidOperationException MissingEncryptionMetadata(string field)
{
return new InvalidOperationException("Missing field \"" + field + "\" in encryption metadata");
}
}
public static ArgumentException AccountMismatch(string accountNameCredential, string accountNameValue)
{
return new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Account Name Mismatch: {0} != {1}", accountNameCredential, accountNameValue));
}
public static InvalidOperationException AccountSasMissingData()
{
return new InvalidOperationException("Account SAS is missing at least one of these: ExpiryTime, Permissions, Service, or ResourceType");
}
public static ArgumentNullException ArgumentNull(string paramName)
{
return new ArgumentNullException(paramName);
}
public static ArgumentException InvalidArgument(string paramName)
{
return new ArgumentException(paramName + " is invalid");
}
public static ArgumentException InvalidResourceType(char s)
{
return new ArgumentException($"""{s}""");
}
public static InvalidOperationException TaskIncomplete()
{
return new InvalidOperationException("Task is not completed");
}
public static FormatException InvalidFormat(string err)
{
return new FormatException(err);
}
public static ArgumentException ParsingConnectionStringFailed()
{
return new ArgumentException("Connection string parsing error");
}
public static ArgumentOutOfRangeException InvalidSasProtocol(string protocol, string sasProtocol)
{
return new ArgumentOutOfRangeException(protocol, "Invalid " + sasProtocol + " value");
}
public static ArgumentException InvalidService(char s)
{
return new ArgumentException($"""{s}""");
}
public static ArgumentException InsufficientStorageTransferOptions(long streamLength, long statedMaxBlockSize, long necessaryMinBlockSize)
{
return new ArgumentException($"""{streamLength}""{statedMaxBlockSize}""{necessaryMinBlockSize}""");
}
public static InvalidDataException HashMismatch(string hashHeaderName)
{
return new InvalidDataException(hashHeaderName + " did not match hash of recieved data.");
}
public static InvalidDataException ChecksumMismatch(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)
{
return new InvalidDataException("Compared checksums did not match. Invalid data may have been written to the destination. Left: " + Convert.ToBase64String(left, Base64FormattingOptions.None) + " Right: " + Convert.ToBase64String(right, Base64FormattingOptions.None));
}
public static InvalidDataException HashMismatchOnStreamedDownload(string mismatchedRange)
{
return new InvalidDataException("Detected invalid data while streaming to the destination. Range " + mismatchedRange + " produced mismatched checksum.");
}
public static ArgumentException PrecalculatedHashNotSupportedOnSplit()
{
return new ArgumentException("Precalculated checksum not supported when potentially partitioning an upload.");
}
public static ArgumentException CannotDeferTransactionalHashVerification()
{
return new ArgumentException("Cannot defer transactional hash verification. Returned hash is unavailable to caller.");
}
public static ArgumentException CannotInitializeWriteStreamWithData()
{
return new ArgumentException("Initialized buffer for StorageWriteStream must be empty.");
}
internal static void VerifyStreamPosition(Stream stream, string streamName)
{
if (stream != null && stream.CanSeek && stream.Length > 0 && stream.Position >= stream.Length)
throw new ArgumentException(streamName + ".Position must be less than " + streamName + ".Length. Please set " + streamName + ".Position to the start of the data to upload.");
}
public static void ThrowIfParamNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException("Param: \"" + paramName + "\" is null");
}
internal static void CheckCryptKeySize(int keySizeInBytes)
{
if (keySizeInBytes != 16 && keySizeInBytes != 24 && keySizeInBytes != 32)
throw new CryptographicException("Specified key is not a valid size for this algorithm.");
}
public static CryptographicException CryptographyAuthTagMismatch()
{
throw new CryptographicException("The computed authentication tag did not match the input authentication tag.");
}
public static ArgumentException CryptographyPlaintextCiphertextLengthMismatch()
{
throw new ArgumentException("Plaintext and ciphertext must have the same length.");
}
public static ArgumentException CryptographyInvalidNonceLength()
{
throw new ArgumentException("The specified nonce is not a valid size for this algorithm.");
}
public static ArgumentException CryptographyInvalidTagLength()
{
throw new ArgumentException("The specified tag is not a valid size for this algorithm.");
}
public static ArgumentException CannotBothBeNotNull(string param0, string param1)
{
return new ArgumentException(param0 + " and " + param1 + " cannot both be set");
}
public static ArgumentOutOfRangeException MustBeGreaterThanOrEqualTo(string paramName, long value)
{
return new ArgumentOutOfRangeException(paramName, $"""{value}");
}
public static ArgumentOutOfRangeException MustBeLessThanOrEqualTo(string paramName, long value)
{
return new ArgumentOutOfRangeException(paramName, $"""{value}");
}
public static ArgumentOutOfRangeException MustBeBetweenInclusive(string paramName, long lower, long upper, long actual)
{
return new ArgumentOutOfRangeException(paramName, $"""{lower}""{upper}""{actual}");
}
public static ArgumentOutOfRangeException MustBeGreaterThanValueOrEqualToOtherValue(string paramName, long value0, long value1)
{
return new ArgumentOutOfRangeException(paramName, $"""{value0}""{value1}");
}
public static ArgumentException StreamMustBeReadable(string paramName)
{
return new ArgumentException("Stream must be readable", paramName);
}
public static InvalidOperationException StreamMustBeAtPosition0()
{
return new InvalidOperationException("Stream must be set to position 0");
}
public static InvalidOperationException TokenCredentialsRequireHttps()
{
return new InvalidOperationException("Use of token credentials requires HTTPS");
}
public static ArgumentException SasCredentialRequiresUriWithoutSas<TUriBuilder>(Uri uri)
{
Uri uri2 = new UriBuilder(uri) {
Query = "[REDACTED]"
}.Uri;
return new ArgumentException(string.Format("You cannot use {0} when the resource URI also contains a Shared Access Signature: {1}\n", "AzureSasCredential", uri2) + "You can remove the shared access signature by creating a " + typeof(TUriBuilder).Name + ", setting " + typeof(TUriBuilder).Name + ".Sas to null, and calling " + typeof(TUriBuilder).Name + ".ToUri.");
}
public static InvalidOperationException SasMissingData(string paramName)
{
return new InvalidOperationException("SAS is missing required parameter: " + paramName);
}
public static InvalidOperationException SasDataNotAllowed(string paramName, string paramNameNotAllowed)
{
return new InvalidOperationException("SAS cannot have the " + paramNameNotAllowed + " parameter when the " + paramName + " parameter is present");
}
public static InvalidOperationException SasDataInConjunction(string paramName, string paramName2)
{
return new InvalidOperationException("SAS cannot have the following parameters specified in conjunction: " + paramName + ", " + paramName2);
}
public static InvalidOperationException SasNamesNotMatching(string builderParam, string builderName, string clientParam)
{
return new InvalidOperationException("SAS Uri cannot be generated. " + builderName + "." + builderParam + " does not match " + clientParam + " in the Client. " + builderName + "." + builderParam + " must either be left empty or match the " + clientParam + " in the Client");
}
public static InvalidOperationException SasNamesNotMatching(string builderParam, string builderName)
{
return new InvalidOperationException("SAS Uri cannot be generated. " + builderName + "." + builderParam + " does not match snapshot value in the URI in the Client. " + builderName + "." + builderParam + " must either be left empty or match the snapshot value in the URI in the Client");
}
public static InvalidOperationException SasServiceNotMatching(string builderParam, string builderName, string expectedService)
{
return new InvalidOperationException("SAS Uri cannot be generated. " + builderName + "." + builderParam + " does specify " + expectedService + ". " + builderName + "." + builderParam + " must either specify " + expectedService + " or specify all Services are accessible in the value.");
}
public static InvalidOperationException SasClientMissingData(string paramName)
{
return new InvalidOperationException("SAS Uri cannot be generated. " + paramName + " in the client has not been set");
}
public static InvalidOperationException SasBuilderEmptyParam(string builderName, string paramName, string sasType)
{
return new InvalidOperationException("SAS Uri cannot be generated. " + builderName + "." + paramName + " cannot be set to create a " + sasType + " SAS.");
}
public static InvalidOperationException SasIncorrectResourceType(string builderName, string builderParam, string value, string clientName)
{
return new InvalidOperationException("SAS Uri cannot be generated. Expected " + builderName + "." + builderParam + " to be set to " + value + " to generate the respective SAS for the client, " + clientName);
}
public static ArgumentException InvalidPermission(char s)
{
return new ArgumentException($"""{s}""");
}
public static ArgumentException ParsingHttpRangeFailed()
{
return new ArgumentException("Could not parse the serialized range.");
}
public static AccessViolationException UnableAccessArray()
{
return new AccessViolationException("Unable to get array from memory pool");
}
public static NotImplementedException NotImplemented()
{
return new NotImplementedException();
}
public static AuthenticationException InvalidCredentials(string fullName)
{
return new AuthenticationException("Cannot authenticate credentials with " + fullName);
}
public static ArgumentException SeekOutsideBufferRange(long index, long inclusiveRangeStart, long exclusiveRangeEnd)
{
return new ArgumentException($"""{index}""{inclusiveRangeStart}""{exclusiveRangeEnd}""");
}
public static ArgumentException VersionNotSupported(string paramName)
{
return new ArgumentException("The version specified by " + paramName + " is not supported by this library.");
}
public static RequestFailedException ClientRequestIdMismatch(Response response, string echo, string original)
{
return new RequestFailedException(response.get_Status(), "Response x-ms-client-request-id '" + echo + "' does not match the original expected request id, '" + original + "'.", (Exception)null);
}
public static ArgumentException TransactionalHashingNotSupportedWithClientSideEncryption()
{
return new ArgumentException("Client-side encryption and transactional hashing are not supported at the same time.");
}
public static void VerifyHttpsTokenAuth(Uri uri)
{
if (uri.Scheme != "https")
throw new ArgumentException("Cannot use TokenCredential without HTTPS.");
}
}
}