private async ValueTask <Comment> TryCatch( ReturningCommentFunction returningCommentFunction) { try { return(await returningCommentFunction()); } catch (NullCommentException nullCommentException) { throw CreateAndLogValidationException(nullCommentException); } catch (InvalidCommentException invalidCommentException) { throw CreateAndLogValidationException(invalidCommentException); } catch (DbUpdateConcurrencyException dbUpdateConcurrencyException) { var lockedCommentException = new LockedCommentException(dbUpdateConcurrencyException); throw CreateAndLogDependencyException(lockedCommentException); } catch (SqlException sqlException) { throw CreateAndLogCriticalDependencyException(sqlException); } catch (DbUpdateException dbUpdateException) { throw CreateAndLogDependencyException(dbUpdateException); } catch (DuplicateKeyException duplicateKeyException) { var alreadyExistsCommentException = new AlreadyExistsCommentException(duplicateKeyException); throw CreateAndLogValidationException(alreadyExistsCommentException); } catch (NotFoundCommentException notFoundCommentException) { throw CreateAndLogValidationException(notFoundCommentException); } catch (InvalidCommentInputException invalidCommentInputException) { throw CreateAndLogValidationException(invalidCommentInputException); } catch (Exception exception) { throw CreateAndLogServiceException(exception); } }
public async void ShouldThrowValidationExceptionOnAddWhenCommentAlreadyExistsAndLogItAsync() { // given DateTimeOffset dateTime = GetRandomDateTime(); Comment randomComment = CreateRandomComment(dateTime); Comment alreadyExistsComment = randomComment; string randomMessage = GetRandomMessage(); string exceptionMessage = randomMessage; var duplicateKeyException = new DuplicateKeyException(exceptionMessage); var alreadyExistsCommentException = new AlreadyExistsCommentException(duplicateKeyException); var expectedCommentValidationException = new CommentValidationException(alreadyExistsCommentException); this.dateTimeBrokerMock.Setup(broker => broker.GetCurrentDateTime()) .Returns(dateTime); this.storageBrokerMock.Setup(broker => broker.InsertCommentAsync(alreadyExistsComment)) .ThrowsAsync(duplicateKeyException); // when ValueTask <Comment> createCommentTask = this.commentService.AddCommentAsync(alreadyExistsComment); // then await Assert.ThrowsAsync <CommentValidationException>(() => createCommentTask.AsTask()); this.loggingBrokerMock.Verify(broker => broker.LogError(It.Is(SameExceptionAs(expectedCommentValidationException))), Times.Once); this.dateTimeBrokerMock.Verify(broker => broker.GetCurrentDateTime(), Times.Once); this.storageBrokerMock.Verify(broker => broker.InsertCommentAsync(alreadyExistsComment), Times.Once); this.dateTimeBrokerMock.VerifyNoOtherCalls(); this.loggingBrokerMock.VerifyNoOtherCalls(); this.storageBrokerMock.VerifyNoOtherCalls(); }