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

Asked

Viewed 123 times

1

I created a Web API that returns a JSON and who is having a problem similar to the question JSONP: status code 200 OK and still returns $.Ajax(... error:Function()...). 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 return of JSON is 200, but in the console displays the error described below
I memorized the API method with the Cors to obtain the conpatibility of origins, however the error persists.

My question is:

Just this snippet of code where I memorize the api method is enough ?

This is the API method: improved at the suggestion of 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

Error image:

inserir a descrição da imagem aqui

1 answer

1

You can handle errors according to the Response status code as you did when you did not find the panel.

What I recommend is to always validate user data entries. In the case of your Convert.ToDateTime exchange for DateTime.TryParse that you can make this validation simple.

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

See that the same action has multiple status returns:

  • 406 Not Acceptable - When user data entry is invalid
  • 404 Not Found - When not to find the panel
  • 417 Expectation Failed - When some 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
    }
}
  • Thanks @Danilo Ribeiro da Silveira but the error persists.

  • When you access the API via GET directly through the URL (outside of your application) does it work? As far as I’m getting from the image you posted, the error is generated by sweetalert and is not an API error. You must be accessing a non-response property that does not exist and passing to sweetalert no?

  • the application works when I call outside the application yes and I got more information and I will edit my post.

  • Your condition to close the modal is wrong. You can only close the modal if it is open. In your case you are denying this. The correct would be if (statusModal.isOpen) { swal.close(); }

  • don’t know ract I took this code from another system that consumes my API and the programmer said that although it is strange is like this rs, by Default is false then there is the negation !.

  • There’s no such thing as Default is false. The method swal.getState() takes the modal information and has the isOpen property that will tell you if there is an open or closed modal. If it is closed it returns false and if it is open returns true is simple. Remove the denial and see that you will no longer give the error. You can test right on the https://sweetalert.js.org/ website and type in the console if (swal.getState().isOpen) { swal.close(); }

  • The type of error Cannot read property 'value' of undefined does not have to do with checking the popup window: Open or Closed so much that I asked the developer to disable the check and persists the error I believe is something related to different domains as in this article enable Cors

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.