private static Exception CreateExceptionIndicatingPhotoHasBeenDeleted() { ObjectNotFoundException ex = new ObjectNotFoundException(Strings.PhotoHasBeenDeleted); ex.Data["Photos.PhotoHasBeenDeletedKey"] = true; return(ex); }
/// <summary> /// Generates an exception depending on the code of the error. /// </summary> /// <returns>An exception which can be thrown.</returns> public Exception GetException() { Exception exception; switch (Code) { /* Argument-Errors */ case 0x30000010: exception = new ArgumentNullException(Message, InnerException?.GetException()); break; case 0x30000011: exception = new ArgumentException(Message, InnerException?.GetException()); break; case 0x30000012: exception = new ArgumentNullException(Data["PropertyName"], Message); break; /* Query-Errors */ case 0x30000030: exception = new ConstraintException(Message, InnerException?.GetException()); break; case 0x30000031: /* PasswordUpdate-Errors */ case 0x000000A0: exception = new ObjectNotFoundException(Message, InnerException?.GetException()); break; /* Security-Errors */ case 0x30000070: case 0x30000071: case 0x30000072: exception = new SecurityException(Message, InnerException?.GetException()); break; /* Login-Errors */ case 0x30000080: exception = new InvalidCredentialException(Message, InnerException?.GetException()); break; /* Registration-Errors */ case 0x30000090: exception = new ArgumentException(Message, InnerException?.GetException()); break; default: exception = new Exception(Message, InnerException?.GetException()); break; } foreach (KeyValuePair <string, string> entry in Data) { exception.Data.Add(entry.Key, entry.Value); } exception.Data.Add("ErrorCode", Code); return(exception); }
public void ConstructorMessageShouldPopulateExceptionMessage() { var message = "This is a really interesting message"; var exception = new ObjectNotFoundException(message); Assert.Equal(message, exception.Message); }
public List <IDomainModel> GetAllSemesters() { var exception = new ObjectNotFoundException("Semesters Weren't Found"); return(new List <IDomainModel> { new ErrorDomainModel(exception, false) }); }
public static ResponseMessage AsHttpResponse(this RequestException e, Uri uri) { return(e switch { InvalidOperationsException _ => new ResponseMessage(HttpStatusCode.BadRequest, e.Message + uri), //TODO: what does the _ mean? ObjectNotFoundException _ => new ResponseMessage(HttpStatusCode.NotFound, "Page not found: " + uri), HttpRequestException exception => new ResponseMessage(exception.StatusCode, exception.Message + uri), _ => throw new Exception("Not a RequestException") });
public TEntity Get(int key) { var result = _session.Get <TEntity>(key); if (ReferenceEquals(result, null)) { var exception = new ObjectNotFoundException(key, typeof(TEntity).Name); throw exception; } return(result); }
public override void SetMailboxOwnerAsSender(MessageItem message) { PublicFolderSession publicFolderSession = base.StoreSession as PublicFolderSession; if (base.CurrentFolder.PropertyBag.GetValueOrDefault <bool>(FolderSchema.MailEnabled)) { Exception ex = null; try { byte[] valueOrDefault = base.CurrentFolder.PropertyBag.GetValueOrDefault <byte[]>(FolderSchema.ProxyGuid); if (valueOrDefault != null && valueOrDefault.Length == 16) { IRecipientSession adrecipientSession = publicFolderSession.GetADRecipientSession(true, ConsistencyMode.PartiallyConsistent); ADRawEntry adrawEntry = adrecipientSession.Read(new ADObjectId(valueOrDefault)) as ADPublicFolder; if (adrawEntry != null) { message.From = new Participant(adrawEntry); return; } } ex = new ObjectNotFoundException(ServerStrings.ExItemNotFound); } catch (ADTransientException ex2) { ex = ex2; } catch (ADExternalException ex3) { ex = ex3; } catch (ADOperationException ex4) { ex = ex4; } catch (DataValidationException ex5) { ex = ex5; } catch (ObjectNotFoundException ex6) { ex = ex6; } if (ex != null) { StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_PFRuleSettingFromAddressFailure, base.CurrentFolder.StoreObjectId.ToHexEntryId(), new object[] { ex }); } } message.From = (publicFolderSession.ConnectAsParticipant ?? new Participant(publicFolderSession.MailboxPrincipal)); }
internal static SCBase GetEffectiveObject(string id, string message) { SCBase result = (SCBase)PC.Adapters.SchemaObjectAdapter.Instance.Load(id); if (result == null) { throw message != null ? new ObjectNotFoundException(message) : ObjectNotFoundException.CreateForID(id); } else if (result.Status != SchemaObjectStatus.Normal) { throw message != null ? new ObjectNotFoundException(message) : ObjectNotFoundException.CreateForID(id); } return(result); }
public virtual T QueryObject <T>(string condition, bool checkExist = false) where T : DbObject, new() { T local = default(T); condition = this.DbRuleContext.GetDbObjectInfo <T>().FixCondition(condition); local = this.DbObjectOperator.Retrieve <T>(condition); if (checkExist && (local == null)) { string format = "The {0} does not exist."; ObjectNotFoundException exception = new ObjectNotFoundException(typeof(T), string.Format(format, typeof(T).Name)); exception.AddExtraData("QueryCondition", condition.Replace("[", "").Replace("]", "").Trim()); throw exception; } return(local); }
public void TestGetObjectData() { var customer = new Customer(); var exception = new ObjectNotFoundException(typeof(Customer), customer.Id); var formatter = new BinaryFormatter(); using(var stream = new MemoryStream()) { formatter.Serialize(stream, exception); stream.Seek(0, SeekOrigin.Begin); var actualException = (ObjectNotFoundException)formatter.Deserialize(stream); Assert.IsNotNull(actualException); Assert.AreEqual(OBJECT_NOT_FOUND_MESSAGE.Form(typeof(Customer).Name, customer.Id), actualException.Message); Assert.AreEqual(typeof(Customer), actualException.ExpectedType); Assert.AreEqual(customer.Id, actualException.ObjectId); } }
public void TestObjectNotFoundExceptionReturnsNotFoundResult() { // Arrange var loggerMock = new Mock <ILogger <ExceptionHandlerFilterAttribute> >(); var logger = loggerMock.Object; var loggerFactoryMock = new Mock <ILoggerFactory>(); loggerFactoryMock.Setup( lf => lf.CreateLogger(It.IsAny <String>())) .Returns(logger); var notFoundMessage = "The object was not found"; var exception = new ObjectNotFoundException(notFoundMessage); var httpContextMock = new Mock <HttpContext>(); var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var actionContext = new ActionContext(httpContextMock.Object, routeData, actionDescriptor); var exceptionContext = new ExceptionContext(actionContext, new List <IFilterMetadata>()); exceptionContext.Exception = exception; exceptionContext.ExceptionHandled = false; // Act var filter = new ExceptionHandlerFilterAttribute(loggerFactoryMock.Object); filter.OnException(exceptionContext); // Assert Assert.NotNull(exceptionContext.Result); Assert.IsType <NotFoundObjectResult>(exceptionContext.Result); var resultObject = (NotFoundObjectResult)(exceptionContext.Result); Assert.IsType <ApiMessageModel>(resultObject.Value); Assert.Equal(notFoundMessage, ((ApiMessageModel)resultObject.Value).Message); // Commented out because LogWarning is an extension method. Need to figure out how to test //loggerMock.Verify(l => l.LogWarning(It.IsAny<EventId>(), exception, notFoundMessage), Times.Once); }
private static void ParseWellKnownErrorNoContent(IRestResponse response) { MinioException error = null; ErrorResponse errorResponse = new ErrorResponse(); foreach (Parameter parameter in response.Headers) { if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.HostId = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.RequestId = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-bucket-region", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.BucketRegion = parameter.Value.ToString(); } } errorResponse.Resource = response.Request.Resource; // zero, one or two segments var resourceSplits = response.Request.Resource.Split(new[] { '/' }, 2, StringSplitOptions.RemoveEmptyEntries); if (HttpStatusCode.NotFound.Equals(response.StatusCode)) { int pathLength = resourceSplits.Length; bool isAWS = response.ResponseUri.Host.EndsWith("s3.amazonaws.com"); bool isVirtual = isAWS && !response.ResponseUri.Host.StartsWith("s3.amazonaws.com"); if (pathLength > 1) { var objectName = resourceSplits[1]; errorResponse.Code = "NoSuchKey"; error = new ObjectNotFoundException(objectName, "Not found."); } else if (pathLength == 1) { var resource = resourceSplits[0]; if (isAWS && isVirtual && response.Request.Resource != string.Empty) { errorResponse.Code = "NoSuchKey"; error = new ObjectNotFoundException(resource, "Not found."); } else { errorResponse.Code = "NoSuchBucket"; BucketRegionCache.Instance.Remove(resource); error = new BucketNotFoundException(resource, "Not found."); } } else { error = new InternalClientException("404 without body resulted in path with less than two components", response); } } else if (HttpStatusCode.BadRequest.Equals(response.StatusCode)) { int pathLength = resourceSplits.Length; if (pathLength > 1) { var objectName = resourceSplits[1]; errorResponse.Code = "InvalidObjectName"; error = new InvalidObjectNameException(objectName, "Invalid object name."); } else { error = new InternalClientException("400 without body resulted in path with less than two components", response); } } else if (HttpStatusCode.Forbidden.Equals(response.StatusCode)) { errorResponse.Code = "Forbidden"; error = new AccessDeniedException("Access denied on the resource: " + response.Request.Resource); } error.Response = errorResponse; throw error; }
private ClientException ParseError(IRestResponse response) { if (response == null) { return new ConnectionException(); } if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode)) { return new RedirectionException(); } if (string.IsNullOrWhiteSpace(response.Content)) { if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) || HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode)) { ClientException e = null; ErrorResponse errorResponse = new ErrorResponse(); foreach (Parameter parameter in response.Headers) { if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.XAmzID2 = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.RequestID = parameter.Value.ToString(); } } errorResponse.Resource = response.Request.Resource; if (HttpStatusCode.NotFound.Equals(response.StatusCode)) { int pathLength = response.Request.Resource.Split('/').Count(); if (pathLength > 1) { errorResponse.Code = "NoSuchKey"; e = new ObjectNotFoundException(); } else if (pathLength == 1) { errorResponse.Code = "NoSuchBucket"; e = new BucketNotFoundException(); } else { e = new InternalClientException("404 without body resulted in path with less than two components"); } } else if (HttpStatusCode.Forbidden.Equals(response.StatusCode)) { errorResponse.Code = "Forbidden"; e = new AccessDeniedException(); } else if (HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode)) { errorResponse.Code = "MethodNotAllowed"; e = new MethodNotAllowedException(); } else { errorResponse.Code = "MethodNotAllowed"; e = new MethodNotAllowedException(); } e.Response = errorResponse; return e; } throw new InternalClientException("Unsuccessful response from server without XML error: " + response.StatusCode); } var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); var stream = new MemoryStream(contentBytes); ErrorResponse errResponse = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream)); string code = errResponse.Code; ClientException clientException; if ("NoSuchBucket".Equals(code)) clientException = new BucketNotFoundException(); else if ("NoSuchKey".Equals(code)) clientException = new ObjectNotFoundException(); else if ("InvalidBucketName".Equals(code)) clientException = new InvalidKeyNameException(); else if ("InvalidObjectName".Equals(code)) clientException = new InvalidKeyNameException(); else if ("AccessDenied".Equals(code)) clientException = new AccessDeniedException(); else if ("InvalidAccessKeyId".Equals(code)) clientException = new AccessDeniedException(); else if ("BucketAlreadyExists".Equals(code)) clientException = new BucketExistsException(); else if ("ObjectAlreadyExists".Equals(code)) clientException = new ObjectExistsException(); else if ("InternalError".Equals(code)) clientException = new InternalServerException(); else if ("KeyTooLong".Equals(code)) clientException = new InvalidKeyNameException(); else if ("TooManyBuckets".Equals(code)) clientException = new MaxBucketsReachedException(); else if ("PermanentRedirect".Equals(code)) clientException = new RedirectionException(); else if ("MethodNotAllowed".Equals(code)) clientException = new ObjectExistsException(); else if ("BucketAlreadyOwnedByYou".Equals(code)) clientException = new BucketExistsException(); else clientException = new InternalClientException(errResponse.ToString()); clientException.Response = errResponse; clientException.XmlError = response.Content; return clientException; }
/// <summary> /// Parse response errors if any and return relevant error messages /// </summary> /// <param name="response"></param> internal static void ParseError(IRestResponse response) { if (response == null) { throw new ConnectionException("Response is nil. Please report this issue https://github.com/minio/minio-dotnet/issues"); } if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode)) { throw new RedirectionException("Redirection detected. Please report this issue https://github.com/minio/minio-dotnet/issues"); } if (string.IsNullOrWhiteSpace(response.Content)) { ErrorResponse errorResponse = new ErrorResponse(); if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) || HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode)) { MinioException e = null; foreach (Parameter parameter in response.Headers) { if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.HostId = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.RequestId = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-bucket-region", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.BucketRegion = parameter.Value.ToString(); } } errorResponse.Resource = response.Request.Resource; if (HttpStatusCode.NotFound.Equals(response.StatusCode)) { int pathLength = response.Request.Resource.Split('/').Count(); bool isAWS = response.ResponseUri.Host.EndsWith("s3.amazonaws.com"); bool isVirtual = isAWS && !(response.ResponseUri.Host.StartsWith("s3.amazonaws.com")); if (pathLength > 1) { errorResponse.Code = "NoSuchKey"; var bucketName = response.Request.Resource.Split('/')[0]; var objectName = response.Request.Resource.Split('/')[1]; if (objectName == "") { e = new BucketNotFoundException(bucketName, "Not found."); } else { e = new ObjectNotFoundException(objectName, "Not found."); } } else if (pathLength == 1) { var resource = response.Request.Resource.Split('/')[0]; if (isAWS && isVirtual && response.Request.Resource != "") { errorResponse.Code = "NoSuchKey"; e = new ObjectNotFoundException(resource, "Not found."); } else { errorResponse.Code = "NoSuchBucket"; BucketRegionCache.Instance.Remove(resource); e = new BucketNotFoundException(resource, "Not found."); } } else { e = new InternalClientException("404 without body resulted in path with less than two components"); } } else if (HttpStatusCode.Forbidden.Equals(response.StatusCode)) { errorResponse.Code = "Forbidden"; e = new AccessDeniedException("Access denied on the resource: " + response.Request.Resource); } e.Response = errorResponse; throw e; } throw new InternalClientException("Unsuccessful response from server without XML error: " + response.ErrorMessage); } if (response.StatusCode.Equals(HttpStatusCode.NotFound) && response.Request.Resource.EndsWith("?location") && response.Request.Method.Equals(Method.GET)) { var bucketName = response.Request.Resource.Split('?')[0]; BucketRegionCache.Instance.Remove(bucketName); throw new BucketNotFoundException(bucketName, "Not found."); } var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); var stream = new MemoryStream(contentBytes); ErrorResponse errResponse = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream)); // Handle XML response for Bucket Policy not found case if (response.StatusCode.Equals(HttpStatusCode.NotFound) && response.Request.Resource.EndsWith("?policy") && response.Request.Method.Equals(Method.GET) && (errResponse.Code.Equals("NoSuchBucketPolicy"))) { ErrorResponseException ErrorException = new ErrorResponseException(errResponse.Message, errResponse.Code); ErrorException.Response = errResponse; ErrorException.XmlError = response.Content; throw ErrorException; } MinioException MinioException = new MinioException(errResponse.Message); MinioException.Response = errResponse; MinioException.XmlError = response.Content; throw MinioException; }
public bool HandleRequest(HttpListenerRequest request, HttpListenerResponse response, string relativePath) { var objectPath = relativePath.Substring(1); Dictionary <string, object> content = null; Exception error = null; var failContent = new Dictionary <string, object>(); UnityMainThreadDispatcher.Instance().EnqueueAndWait(() => { try { if (objectPath == "") { content = SceneExplorer.InspectRoot(); } else { var gameObject = GameObject.Find(objectPath); if (gameObject == null) { error = new ObjectNotFoundException(objectPath); return; } content = SceneExplorer.InspectGameObject(gameObject); var idString = request.QueryString.Get("id"); var componentId = 0; var findTargetId = !string.IsNullOrEmpty(idString) && int.TryParse(idString, out componentId); if (findTargetId) { content["component"] = SceneExplorer.CreateRemoteView(gameObject .GetComponents <Component>() .First(comp => comp.GetInstanceID() == componentId)); } } } catch (Exception exception) { error = exception; } }); if (error != null) { response.SendJson(JsonReponse.Error(error.Message)); } else if (failContent.Count > 0) { response.SendJson(JsonReponse.Fail(failContent)); } else { response.SendJson(JsonReponse.Success(content)); } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="HibernateObjectRetrievalFailureException"/> class. /// </summary> /// <param name="ex">The ex.</param> public HibernateObjectRetrievalFailureException(ObjectNotFoundException ex) : base(ex.PersistentClass, ex.Identifier, ex.Message, ex) { }
public override IAsyncResult BeginExecute(AsyncCallback executeCallback, object state) { this.executionAsyncResult = new LazyAsyncResult(null, state, executeCallback); this.performanceCounter.Start(OperationType.EndToEnd); try { this.InitializeSyncMetadata(); base.UpdateSyncMetadataOnBeginSync(); } catch (StorageTransientException ex) { ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute: failed with StorageTransientException", ex); this.executionAsyncResult.InvokeCallback(ex); return(this.executionAsyncResult); } catch (StoragePermanentException ex2) { ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute: failed with StoragePermanentException", ex2); this.executionAsyncResult.InvokeCallback(ex2); return(this.executionAsyncResult); } ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute"); Exception value = null; Uri uri; string b; if (this.recordedSiteUrl != null && this.webCollectionUrl != null && this.TryGetSharePointSiteUrlAndTitle(this.webCollectionUrl, this.webId, out uri, out b, out value)) { if (UriComparer.IsEqual(this.recordedSiteUrl, uri)) { if (string.Equals(this.displayName, b)) { goto IL_286; } } try { IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, null, CultureInfo.InvariantCulture.LCID, false, ConsistencyMode.IgnoreInvalid, null, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(this.orgId), 189, "BeginExecute", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\LinkedFolder\\MaintenanceSynchronizer.cs"); ADUser aduser = tenantOrRootOrgRecipientSession.FindByExchangeGuid(this.TeamMailboxGuid) as ADUser; if (aduser == null) { value = new ObjectNotFoundException(new LocalizedString("Cannot find the team mailbox by mailbox guid " + this.TeamMailboxGuid)); } else { aduser.SharePointUrl = uri; aduser.DisplayName = b; tenantOrRootOrgRecipientSession.Save(aduser); ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.BeginExecute: updated new SharePoint site URL: " + uri); if (!UriComparer.IsEqual(this.recordedSiteUrl, uri)) { RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn, this.mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, QueueType.TeamMailboxDocumentSync, this.mailboxSession.MailboxOwner.MailboxInfo.OrganizationId, "Maintenance Synchronizer", tenantOrRootOrgRecipientSession.LastUsedDc, SyncOption.Default); RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn, this.mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, QueueType.TeamMailboxMembershipSync, this.mailboxSession.MailboxOwner.MailboxInfo.OrganizationId, "Maintenance Synchronizer", tenantOrRootOrgRecipientSession.LastUsedDc, SyncOption.Default); } } } catch (DataSourceOperationException ex3) { value = ex3; } catch (DataValidationException ex4) { value = ex4; } catch (TransientException ex5) { value = ex5; } } IL_286: this.executionAsyncResult.InvokeCallback(value); return(this.executionAsyncResult); }
private ClientException ParseError(IRestResponse response) { if (response == null) { return(new ConnectionException("Response is nil. Please report this issue https://github.com/minio/minio-dotnet/issues")); } if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode)) { return(new RedirectionException("Redirection detected. Please report this issue https://github.com/minio/minio-dotnet/issues")); } if (string.IsNullOrWhiteSpace(response.Content)) { if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) || HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode)) { ClientException e = null; ErrorResponse errorResponse = new ErrorResponse(); foreach (Parameter parameter in response.Headers) { if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.HostId = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.RequestId = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-bucket-region", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.BucketRegion = parameter.Value.ToString(); } } errorResponse.Resource = response.Request.Resource; if (HttpStatusCode.NotFound.Equals(response.StatusCode)) { int pathLength = response.Request.Resource.Split('/').Count(); if (pathLength > 1) { errorResponse.Code = "NoSuchKey"; var objectName = response.Request.Resource.Split('/')[1]; e = new ObjectNotFoundException(objectName, "Not found."); } else if (pathLength == 1) { errorResponse.Code = "NoSuchBucket"; var bucketName = response.Request.Resource.Split('/')[0]; e = new BucketNotFoundException(bucketName, "Not found."); } else { e = new InternalClientException("404 without body resulted in path with less than two components"); } } else if (HttpStatusCode.Forbidden.Equals(response.StatusCode)) { errorResponse.Code = "Forbidden"; e = new AccessDeniedException("Access denied on the resource: " + response.Request.Resource); } e.Response = errorResponse; return(e); } throw new InternalClientException("Unsuccessful response from server without XML error: " + response.StatusCode); } var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); var stream = new MemoryStream(contentBytes); ErrorResponse errResponse = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream)); ClientException clientException = new ClientException(errResponse.Message); clientException.Response = errResponse; clientException.XmlError = response.Content; return(clientException); }
public IDomainModel GetSemester(Guid semesterId) { var exception = new ObjectNotFoundException("Semester Wasn't Found"); return(new ErrorDomainModel(exception, false)); }
private ClientException ParseError(IRestResponse response) { if (response == null) { return(new ConnectionException()); } if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode)) { return(new RedirectionException()); } if (string.IsNullOrWhiteSpace(response.Content)) { if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) || HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode)) { ClientException e = null; ErrorResponse errorResponse = new ErrorResponse(); foreach (Parameter parameter in response.Headers) { if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.HostID = parameter.Value.ToString(); } if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase)) { errorResponse.RequestID = parameter.Value.ToString(); } } errorResponse.Resource = response.Request.Resource; if (HttpStatusCode.NotFound.Equals(response.StatusCode)) { int pathLength = response.Request.Resource.Split('/').Count(); if (pathLength > 1) { errorResponse.Code = "NoSuchKey"; e = new ObjectNotFoundException(); } else if (pathLength == 1) { errorResponse.Code = "NoSuchBucket"; e = new BucketNotFoundException(); } else { e = new InternalClientException("404 without body resulted in path with less than two components"); } } else if (HttpStatusCode.Forbidden.Equals(response.StatusCode)) { errorResponse.Code = "Forbidden"; e = new AccessDeniedException(); } else if (HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode)) { errorResponse.Code = "MethodNotAllowed"; e = new MethodNotAllowedException(); } else { errorResponse.Code = "MethodNotAllowed"; e = new MethodNotAllowedException(); } e.Response = errorResponse; return(e); } throw new InternalClientException("Unsuccessful response from server without XML error: " + response.StatusCode); } var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); var stream = new MemoryStream(contentBytes); ErrorResponse errResponse = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream)); string code = errResponse.Code; ClientException clientException; if ("NoSuchBucket".Equals(code)) { clientException = new BucketNotFoundException(); } else if ("NoSuchKey".Equals(code)) { clientException = new ObjectNotFoundException(); } else if ("InvalidBucketName".Equals(code)) { clientException = new InvalidKeyNameException(); } else if ("InvalidObjectName".Equals(code)) { clientException = new InvalidKeyNameException(); } else if ("AccessDenied".Equals(code)) { clientException = new AccessDeniedException(); } else if ("InvalidAccessKeyId".Equals(code)) { clientException = new AccessDeniedException(); } else if ("BucketAlreadyExists".Equals(code)) { clientException = new BucketExistsException(); } else if ("ObjectAlreadyExists".Equals(code)) { clientException = new ObjectExistsException(); } else if ("InternalError".Equals(code)) { clientException = new InternalServerException(); } else if ("KeyTooLong".Equals(code)) { clientException = new InvalidKeyNameException(); } else if ("TooManyBuckets".Equals(code)) { clientException = new MaxBucketsReachedException(); } else if ("PermanentRedirect".Equals(code)) { clientException = new RedirectionException(); } else if ("MethodNotAllowed".Equals(code)) { clientException = new ObjectExistsException(); } else if ("BucketAlreadyOwnedByYou".Equals(code)) { clientException = new BucketExistsException(); } else { clientException = new InternalClientException(errResponse.ToString()); } clientException.Response = errResponse; clientException.XmlError = response.Content; return(clientException); }