Search code examples
angularnswagnswagstudio

Nswag/Angular display API error message in error event


First of All I was using the CQRS architecture for the back-end API and using NSWAG as an API connection; that generates API Endpoints in service proxy for the front-end Angular.

I did simple validation for my POST API, while testing the created API the result was different in DevTools.

In Network tab the validation that i expected was occured however in Console tab the result is different; As a matter of fact that result is i need.

Here's my problem. In detail with image

code for API call

     saveLocationType(createLocationTypeCommand){
    this.tenantService.createLocationType(createLocationTypeCommand).subscribe(result => {
   // Do Something
    }, error => {
      console.log(error); 
    })
  }

This is the validation result coming from my API in Network Tab that was correct. enter image description here

This is my problem in Console the result here must be the same in Network Tab. enter image description here

I believe the result in console was coming from service proxy since that's the one generates/formatting the APIs for the front-end.

Is there a way to configure the generated service proxy of NSWAG? or is there other way to show the error message in Console tab same in Network Tab?


Solution

  • I solved my problem using these reference:

    Snippet in C# Web API that i implemented to fixed my problem

      [HttpPost("setup/locationType", Name = "createLocationType")]
            [ProducesResponseType((int)HttpStatusCode.OK)]
            [ProducesResponseType(typeof(ValidationProblemDetails), (int)HttpStatusCode.BadRequest)]
            public async Task<IActionResult> CreateLocationTypeAsync([FromBody] CreateLocationTypeCommand command)
            {
                try
                {
                    var commandResult = await _mediator.Send(command);
    
                    if (!commandResult)
                    {
                        return BadRequest();
                    }
    
                    return Ok();
                }
                catch(Exception ex)
                {
                    var problemDetails = new ValidationProblemDetails
                    {
                        Status = (int)HttpStatusCode.BadRequest,
                        Type = "",
                        Title = "Create Location Type",
                        Detail = ex.Message,
                        Instance = HttpContext.Request.Path
                    };
    
                    return new ObjectResult(problemDetails)
                    {
                        ContentTypes = { "application/problem+json" },
                        StatusCode = (int)HttpStatusCode.BadRequest,
                    };
                }
    
            }
    
    

    Thanks!