EXT JS proxy throwing error - json

The following proxy has been throwing listener exceptions at sporadic moments. I added a timeout:100 to try and recreate the error and it successfully throws it every time.
However the error sometimes occurs for a request under the default of 30 seconds.
Is there anything else, besides the timeout, that would cause the listener exceptions to be thrown? There is nothing informative in the error logs.
proxy: {
type: 'rest',
url: '/data/identity',
reader: {
type: 'json',
successProperty: 'success',
messageProperty: 'message'
},
writer: {
type: 'json',
writeAllFields: true
},
listeners: {
exception: function(proxy, response, operation, eOpts){
if(operation.action === "read"){
Ext.Msg.alert('Error Retrieving', response.responseText);
}else if(operation.action === "create"){
Ext.Msg.alert('Error Creating', response.responseText);
}else if(operation.action === "update"){
Ext.Msg.alert('Error Updating', response.responseText);
}
}
}
}

The operation object contains information about the error. It has a method getError() to get a description of the error. This would probably show you the error message you are looking for :
var error = operation.getError()
if(error.status && error.statusText){
Ext.Msg.alert('Error', 'Error ' + error.status + ': ' + error.statusText)
}
This is the code I use in my proxy. In addition to display the error thrown during the operation, it also displays any error that happened on the server side (I catch them and send them in the msg property of the json data). The reason why I check for navigator.onLine is that my application uses Application Cache.
listeners: {
exception: function(proxy, response, operation){
var error = operation.getError(),
errorMsg;
if(!navigator.onLine){
errorMsg = Lang._('You are not connected to internet.')
} else if(Ext.isObject(error)){
if(error.status && error.statusText)
errorMsg = 'Error ' + error.status + ': ' + error.statusText
else
errorMsg = Ext.encode(error)
} else if(response.responseText) {
var json = Ext.decode(response.responseText);
errorMsg = json.msg
}
Ext.Msg.show({
title: Lang._('Error loading external data'),
msg: errorMsg,
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
})
}
}

Related

How to use postman to test the call of my api

i am currently building an frontend app to display a generated qr code from an api. I started to implement the code but got a problem with the parsing of the response
here is the frontend code with the call
<template>
<div>
<p>test</p>
</div>
</template>
<script>
// Configuration
let myConfiguration = {
"Account" : "CH4431999123000889012",
"CreditorName" : "Muster AG",
"CreditorAddress1" : "Hauptstrasse 1",
"CreditorAddress2" : "8000 Zürich",
"CreditorCountryCode" : "CH",
"DebtorName" : "LivingTech GmbH",
"DebtorAddress1" : "Dörflistrasse 10",
"DebtorAddress2" : "8057 Zürich",
"DebtorCountryCode" : "CH",
"Amount" : "1.50",
"ReferenceNr" : "21000000000313947143000901",
"UnstructuredMessage" : "Mitteilung zur Rechnung",
"Currency" : "CHF",
"QrOnly" : "false",
"Format" : "PDF",
"Language" : "DE"
}
// Call function to create invoice
let myFile = generateQrInvoice(myConfiguration);
// Work with binary data
if(myFile != null) {
// ...
}
function generateQrInvoice(myRequestConfiguration) {
// Main configuration
let myEndpointUrl = "http://qrbillservice.livingtech.ch";
let myEndpointPath = "/api/qrinvoice/create/";
let myApiKey = "(falseApiKey)";
// GET parameters
let myGetParams = new URLSearchParams(myRequestConfiguration);
// Perform request
fetch(myEndpointUrl + myEndpointPath + "?" + myGetParams, {
method: "GET",
mode: "cors",
cache: "no-cache",
headers: {
"APIKEY": myApiKey,
"Accept": "application/json"
}
}).then(function (myResponse) {
try {
// Check status
if(myResponse.status == 200) {
// Read and parse JSON
let myJsonObject = JSON.parse(myResponse);
// Check if error
if(myJsonObject["isSuccessed"] == "true") {
if("base64Content" in myJsonObject && myJsonObject["base64Content"].trim() != "") {
// E.g. send file to client
let myBlob = new Blob(atob(myJsonObject["base64Content"]), {type: "application/pdf"});
let myBlobUrl = URL.createObjectURL(myBlob);
window.open(myBlobUrl);
// Return data
return atob(myJsonObject["base64Content"]);
} else {
throw "no data provided";
}
} else {
throw myJsonObject["message"];
}
} else {
throw "status code " . myResponse.status;
}
}
catch(e) {
// Handle exception
console.warn("Error: " + e.message, e);
return null;
}
}).catch(function (err) {
// Handle exception
console.warn("Error: " + err.message, err);
return null;
});
}
</script>
and here is the response i get when i inspect on the browser :
Error: Unexpected token 'o', "[object Response]" is not valid JSON SyntaxError: Unexpected token 'o', "[object Response]" is not valid JSON
at JSON.parse (<anonymous>)
at app.vue:61:42
I didn't write the apikey here but it is written on my code.
As it has been a long time since i didn't code like this, i don't really see yet how to tackle the problem. I tried to test with postman but it appears my request is not good yet.
If someone has an idea, i would be very happy to learn.
Thank you very much in advance,
Eugene
So i test myResponse and it is a JSON.
However the problem remains : i saw in the console that the api answers successfully api response
So i figured that i could just replace
let myJsonObject = JSON.parse(myResponse)
by
let myJsonObject = myResponse
and try to see what goes.
Now it goes directly in the catch(e) and send me an error response.
It looks like in my code, i don't go in the right direction to use the information i got from the api.
Here is partially the information i got : {"isSuccessed":true,"statusCode":200,"mimeType":"application/pdf","message":"QrBill is successfully generated","isQrOnly":false,"errors":"null","base64Content":(here is the content, i didn't added because it is quite long)}
my question therefore is how could recover the pdf and show it to the end user?

How to ask a confirmation before uploading a file (primeng)?

I'm trying to ask for a confirmation before upload the file so the server, currently I have this HTML code:
<p-fileUpload mode="basic" name="file" url="{{urlUpload}}" chooseLabel="Upload CSV (onBeforeSend)="onBeforeSend($event)">
Then, I have this TS code:
onBeforeSend (event): void {
const token = this.service.getTokenSession();
event.xhr.setRequestHeader('Authorization', 'Bearer ' + token);
this.confirmationService.confirm({
message: 'Are you sure to continue?',
header : 'Confirmation',
accept : () => {
this.service.showLoader();
this.onUpload(event);
},
reject: () => {}
});
}
onUpload(event): void {
this.msgsPage = [];
try {
const response = JSON.parse(event.xhr.response);
console.log(response)
if (!response.ok) {
this.errorModalService.show('There was an error');
this.flagResultLoadErrors = true;
let c = 0;
for (let msg of response.map.errors) {
c++;
this.msgsPage.push({
detail : msg,
severity: 'error',
summary : 'Error ' + c,
});
}
}
} catch (e) {
this.errorModalService.show('Unknown error');
console.log(e)
} finally {
this.service.hideLoader();
}
}
With this, I tried to block the request, but it didn't happen, what I got is that the file is sent to the server before the confirmation dialog.
Also, I'm getting this error when I tried to get the response:
SyntaxError: Unexpected end of JSON input
Hope you can help me.
You can't block from that event. It is just an event emitted from the component.
https://github.com/primefaces/primeng/blob/master/src/app/components/fileupload/fileupload.ts#L367
You will need to use the custom uploadHandler.
<p-fileUpload name="myfile[]" customUpload="true" (uploadHandler)="myUploader($event)"></p-fileUpload>
myUploader(event) {
//event.files == files to upload
}
SyntaxError: Unexpected end of JSON input
This one means the response you are getting from the xhr response is not JSON, but you are trying to parse it. Check network tab to see what the response from the server is.

Requested JSON Parse Error when sending two variables values using $.ajax

The code below is inside script of view.cshtml
All I want to achieve is parse the values MinDate and MaxDate into my controller.
But I always get Requested JSON Parse Error. I used the variable MinDate and MaxDate in data {}
same error i even tried to pass the raw default MinDate and MaxDate into data {}
and I still got same error. What could the problem be?
// Add event listeners to the two range filtering inputs
$('#FromDate').on("keyup change", function () {
var MinDate = $.datepicker.formatDate("dd-mm-yy", $("#FromDate").datepicker("getDate"));
var MaxDate = $.datepicker.formatDate("dd-mm-yy", $("#ToDate").datepicker("getDate"));
$.ajax({
url: '/CAACAllExpense/LEADFilter',
data: { 'data1': "12-10-2019", 'data2': "14-10-2019" },
dataType: 'json',
success: function (data) {
alert(data.success);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#Error').html(msg);
},
});
});
data needs to be a string:
data = JSON.stringify({ 'data1': "12-10-2019", 'data2': "14-10-2019" })

JSON parseerror when % is in data content

I need to fix problem on site, and i can't figure out how. I have function which dynamically download articles, but when it contain % sign it throws parseerror. Can anyone help me to change this function to work with % sign and explain me that JSON behavior?
$('.funfan_more').click(function(){
if((offset*fun)+fun>=fun_count && (offset*fan)+fan>=fan_count){
$('.load_more').html('').css('height','30px').css('background','none');
}
ajaxLoader.show();
if(!loading) {
loading = true;
$.ajax('<?php echo URL::site('load_posts'); ?>',{
async: false,
type: 'GET',
data: {
offset: offset
},
dataType: 'json',
cache: false,
error: function( jqXHR, textStatus, errorThrown ) {
alert('Ups, some we have some' + textStatus + ' error here.');
},
success: function( data, textStatus, jqXHR ) {
$('.ff_left').append(data.a);
$('.ff_right').append(data.b);
offset++;
setTimeout(function(){
Cufon.refresh();
loading = false;
ajaxLoader.hide();
}, 1000);
}
});
}
return false;
});
I found the solution. Script wrongly preapared feed for site. It was a Kohana object pushed to string witch sprintf function, which was giving error if % was in website feed. Changing sprintf for normal casting to String type helped.

Handling 404 exceptions in Sencha touch Store with an ajax proxy

I'm trying to make my code a little more robust, by handling all sorts of exceptions that may occur. One may be a 404 exception on a Json web request. It looks like the callback method of store.load isn't called when the Json request gets a 404 exception.
The code:
Ext.regModel('Activiteit', {
fields: [
{ name: 'id', type: 'int' },
{ name: 'ServerId', type: 'int', mapping: 'Id' },
{ name: 'Title', type: 'string' },
{ name: 'Description', type: 'string' },
],
});
Ext.regApplication({
name: 'App',
launch: function () {
console.log('launch');
var ajaxActiviteitStore = new Ext.data.Store({
model: "Activiteit",
storeId: 'ajaxActiviteitStore',
proxy: {
type: 'ajax',
url: '/senchatest/Activiteit/Gett/',
reader: {
type: 'json',
root: 'activiteiten'
}
}
});
ajaxActiviteitStore.load(function (records, operation, success) {
//the operation object contains all of the details of the load operation
console.log(success);
});
}
});
This results in a "Uncaught TypeError: Cannot read property 'length' of undefined" exception on line 7212 of sencha-touch-debug.js. I'm using version 1.1.0 of sencha touch.
The stacktrace:
Uncaught TypeError: Cannot read property 'length' of undefined
Ext.data.Store.Ext.extend.loadRecords sencha-touch-debug.js:7212
Ext.data.Store.Ext.extend.onProxyLoad sencha-touch-debug.js:7024
(anonymous function) sencha-touch-debug.js:8742
Ext.data.Connection.Ext.extend.onComplete sencha-touch-debug.js:17566
Ext.data.Connection.Ext.extend.onStateChange sencha-touch-debug.js:17513
(anonymous function) sencha-touch-debug.js:3421
What am I doing wrong here?
I found a workaround by adding a listener to the proxy that listens to the 'exception' event, but I'd rather like the callback function of the store load to be called. Am I doing something wrong, or is this default behaviour?
Thanks,
Sander
I encounter the same Exception (Uncaught TypeError: Cannot read property 'length' of undefined) with an AjaxProxy (ST 1.1.0) if the server return an error (404, 500, ...).
Actually, I think the problem is in the Ext.data.AjaxProxy.createRequestCallback method.
I solved my problem with a dirty code like this:
var ajaxActiviteitStore = new Ext.data.Store({
model: "Activiteit",
storeId: 'ajaxActiviteitStore',
proxy: {
type: 'ajax',
url: 'some nonexistent url',
reader: {
type: 'json',
root: 'activiteiten'
},
listeners: {
exception: function(store, response, op) {
console.log('Exception !');
// hack to avoid js exception :
// TypeError: 'undefined' is not an object (evaluating 'records.length')
// on line sencha-touch-debug-1-1-0.js:7212
op.records = [];
}
}
}
});
Hope this can help, and I will look to open an issue on sencha-touch forum.
I think you have another problem that unexisted url. Nevertheless, try this:
var storeException = 0;
this.ajaxActiviteitStore = new Ext.data.Store({
model: "Activiteit",
storeId: 'ajaxActiviteitStore',
proxy: {
type: 'ajax',
url: 'some nonexistent url',
reader: {
type: 'json',
root: 'activiteiten'
},
listeners: {
exception: {
fn: function(proxy, response, operation ) {
// you can parse `response.responseText` to make some decisions
storeException = 404;
}
}
}
}
});
this.ajaxActiviteitStore.load({
scope: this,
callback: function (records, operation, success) {
if (storeException==0) {
// do something
} else {
alert('Service unaviable');
}
}
});