public static async Task <HttpResponseMessage> Run
        (
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "heroes/{id}")] ChangeHeroNameCommand command,
            HttpRequestMessage request,
            string id,
            [Inject] IHeroService heroService,
            ILogger logger
        )
        {
            try
            {
                await heroService.ChangeName(id, command);

                return(request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex) when(ex is ArgumentNullException || ex is FailedValidationException || ex is InvalidOperationException)
            {
                return(request.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (NotFoundException)
            {
                return(request.CreateResponse(HttpStatusCode.NotFound));
            }
            catch (DuplicateException)
            {
                return(request.CreateResponse(HttpStatusCode.Conflict));
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw;
            }
        }
Exemple #2
0
        public async Task <IActionResult> Put(string id, [FromBody] ChangeHeroNameCommand command)
        {
            try
            {
                await _heroService.ChangeName(id, command);

                return(Ok());
            }
            catch (Exception exception) when(exception is ArgumentException || exception is FailedValidationException || exception is InvalidOperationException)
            {
                return(BadRequest());
            }
            catch (DocumentNotFoundException)
            {
                return(NotFound());
            }
            catch (DuplicateDocumentException)
            {
                return(StatusCode((int)HttpStatusCode.Conflict));
            }
        }
        public async Task ChangeName(string id, ChangeHeroNameCommand command)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (command.Id != id)
            {
                throw new InvalidOperationException();
            }

            if (!command.IsValid())
            {
                throw new FailedValidationException();
            }

            Hero hero = await _heroRepository.FindOneById(id);

            if (hero == null)
            {
                throw new DocumentNotFoundException();
            }

            hero.ChangeName(command.Name);

            if (await _heroRepository.IsDuplicate(hero))
            {
                throw new DuplicateDocumentException();
            }

            await _heroRepository.Update(hero);
        }