How to ensure that the generated JSON does not return error to the Client?

1

I created a Web API that returns a JSON and has a problem similar to the JSONP: status code 200 OK and anyway returns $ .Ajax (... error: function () ...) . The client consumes the API with Nodes like this:

refresh() {
        axios
            .get('${URL}"${this.generateDate()}"')

            .then(resp => {
                console.log(resp);
                this.setState({ ...this.state, services: resp.data, loading: false });

                let statusModal = swal.getState();

                //if (!statusModal.isOpen) {
                //  swal.close();
                //}
            })
            .catch(e => {
                console.log('O erro é =>', e);
                //swal('Ocorreu algum problema!', 'Entre em contato com o responsável', 'error');
                //this.setState({ ...this.state, loading: false });
            });
    }

The JSON return is 200, but on the console it displays the error described below. I decorated the API method with Cors for source compatibility, however the error persists.

My question is:

Only this snippet where I adhere to the api method is enough?

This is the API method: improved as suggested by Danilo Ribeiro da Silva

    [EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "*")]
    [RoutePrefix("api/monitora")]
    public class MonitoraController : ApiController
    {

        // GET: api/Painel/5
        [Route("GetPainel")]
        public IHttpActionResult GetPainel(string dtHoraExecuta)
        {
            try
            {
                DateTime dt = DateTime.MinValue;
                if (!DateTime.TryParse(dtHoraExecuta.Replace("\"", ""), out dt))
                    return StatusCode(HttpStatusCode.NotAcceptable); // 406


                List<ProductType> lreturn = new List<ProductType>();
                PainelMonitoracaoBusiness obj = new PainelMonitoracaoBusiness();
                dt = Convert.ToDateTime(Convert.ToDateTime(dtHoraExecuta.Replace("\"", "")));

                var _painel = obj.ObterDadosPainel(dt);

                if (_painel == null)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(string.Format("Não foram encontrado dados para esse período. = {0}", dtHoraExecuta)),
                        ReasonPhrase = "Serviços não encontrados."
                    };
                    throw new HttpResponseException(resp);
                }

                for (int i = 0; i < _painel.Count; i++)
                {

                    ProductType prd = new ProductType();

                    for (int z = 0; z < _painel[i].lservices.Count; z++)
                    {
                        if (_painel[i].ID_SERVICO == _painel[i].lservices[z].ID_SERVICO)
                        {
                            prd.productType = _painel[i].productType;
                            SubServico subServico = new SubServico();
                            subServico.statusAll = _painel[i].lservices[z].statusAll;
                            subServico.subtype = _painel[i].lservices[z].subtype;

                            Info infoAbertura = new Info();
                            infoAbertura.mount = _painel[z].lservices[0].info[0].mount;
                            infoAbertura.status = _painel[z].lservices[0].info[0].status;
                            infoAbertura.type = _painel[z].lservices[0].info[0].type;

                            Info infoFechamento = new Info();
                            infoFechamento.mount = _painel[z].lservices[0].info[1].mount;
                            infoFechamento.status = _painel[z].lservices[0].info[1].status;
                            infoFechamento.type = _painel[z].lservices[0].info[1].type;

                            subServico.info.Add(infoAbertura);
                            subServico.info.Add(infoFechamento);

                            prd.services.Add(subServico);
                        }                        
                    }
                    lreturn.Add(prd);
                }

                return Ok(lreturn);
            }
            catch (Exception)
            {
                return StatusCode(HttpStatusCode.ExpectationFailed); // 417
            }
        }

This is the error I captured in the browser:

 erro é => TypeError: Cannot read property 'value' of undefined

Image of the error:

    
asked by anonymous 18.09.2018 / 14:40

1 answer

1

You can treat errors according to the status code of the response just like you did when you did not find the panel.

What I recommend is always validate the data entries of users. In case your Convert.ToDateTime exchange with DateTime.TryParse you can do this validation in a simple way.

I always put a try catch block with a return that does not show the error to the user.

See that the same action has multiple status returns:

  • 406 Not Acceptable - When user input is Invalid
  • 404 Not Found - When you can not find the panel
  • 417 Expectation Failed - When an internal error occurs
  • 200 OK - When successful

Example below:

public IHttpActionResult GetPainel(string dtHoraExecuta)
{
    try
    {
        // Verifica se os dados passados pelo cliente são válidos
        if (!ModelState.IsValid)
            return StatusCode(HttpStatusCode.NotAcceptable); // 406

        // Verifica se os dados passados pelo cliente são válidos
        DateTime dt = DateTime.MinValue;
        if(!DateTime.TryParse(dtHoraExecuta.Replace("\"", ""), out dt))
            return StatusCode(HttpStatusCode.NotAcceptable); // 406

        // Obtem os dados...
        if (dados == null)
            return NotFound();

        //...

        return Ok(dados)
    }
    catch (Exception)
    {
        // Erro interno do servidor
        return StatusCode(HttpStatusCode.ExpectationFailed); // 417
    }
}
    
18.09.2018 / 15:25