public async Task <ActionResult <string> > TrySendMessages() { string content; try { var newMessages = _dbContext.Set <Message>().AsNoTracking().Where(m => !m.IsReceived).ToList(); content = _smsSender.TrySendMessages(newMessages); if (TryParseContent(content, out var result) && string.IsNullOrEmpty(result.ErrCode)) { var saveMegsRespTask = _dbContext.Set <MessageResponse>() .AddRangeAsync(result.Messages); MarkMessagesAsReceived(result.Messages); await Task.WhenAll(saveMegsRespTask); } else { _dbContext.Set <CriticalError>().Add(new CriticalError(result.ErrCode)); _dbContext.SaveChanges(); return(StatusCode(500)); } } catch (Exception e) { var error = GetInnerErrorDescription(e); _dbContext.SaveChanges(); return(StatusCode(500, error)); } _dbContext.SaveChanges(); return(content); }