public ActionResult <Bird> CreateNewBird([FromBody] BirdForCreation bird) { try { var newBird = _birdObservationservice.AddNewBirdAndLogInfo(bird, _logger); return(Ok(newBird)); } catch (Exception error) { _logger.LogError(error.ToString()); if (error is InvalidOperationException) { ModelState.AddModelError("Description", error.Message); return(BadRequest(ModelState)); } return(StatusCode(500)); } }
public Bird AddNewBirdAndLogInfo(BirdForCreation bird, ILogger <BirdObservationController> _logger) { var duplicatedBirdName = Birds.FirstOrDefault(b => b.BirdName == bird.BirdName); if (duplicatedBirdName != null) { throw new InvalidOperationException("This bird is already in the list."); } var maxBirdId = Birds.Max(b => b.Id); var newId = ++maxBirdId; var newBird = new Bird(newId, bird.BirdName); Birds.Add(newBird); var jsonData = JsonConvert.SerializeObject(Birds, Formatting.Indented); File.WriteAllText(path, jsonData); logNewBirdInfo(newBird, _logger); return(newBird); }