Titanium Appcelerator - HTTPClient - onload - custom exception - exception

I am using Titanium Studio (build: 3.4.0.201409261227) and I am trying to catch an exception within the "onload" callback of Ti.Network.HTTPClient.
But that's not possible, I am getting the "Red Screen" with "Application Error" and I am not able to catch the exception.
Anyone an idea?
try {
var tiHTTPClient = Ti.Network.createHTTPClient({
onload : function(e) {
throw 'EXCEPTION';
}
});
tiHTTPClient.open( 'GET', 'http://www.google.com' );
tiHTTPClient.send();
}
catch( e ) {
alert( 'E: ' + e.message );
}
Outside the "onload" function, it's easily possible via:
try {
throw 'EXCEPTION';
}
catch( e ) {
alert( 'E: ' + e.message );
}

This might be the correct answer or at least the explanation :
BTW, the reason your try...catch blog makes no difference is that "invoke" succeeds -- it's an asynchronous call so it just returns control immediately, and you therefore pass right through the try block without any problems.
Blockquote
And one solution could be:
var exceptionHandling = function( msg ) {
alert( 'E: ' + msg );
};
var tiHTTPClient = Ti.Network.createHTTPClient({
onload : function(e) {
exceptionHandling('EXCEPTION');
}
});
tiHTTPClient.open( 'GET', 'http://www.google.com' );
tiHTTPClient.send();

Related

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.

object keys are undefined in if conditional, but inside the if statement I can access it

As the title states, I have a variable which is a javascript object, i'm comparing it with another js object by stringifying them. The problem is that the variable is completely accessible without calling the keys, so these
if(JSON.stringify(response) == JSON.stringify(lastcmd))
if(JSON.stringify(response.id) == JSON.stringify(lastcmd))
work perfectly fine, but accessing lastcmd's id key will cause it to throw undefined.
if(JSON.stringify(response) == JSON.stringify(lastcmd.id))
full code link here
Edit: Here's the JSON
{ "id" : "001", "app": "msgbox", "contents": { "title": "Newpaste", "message": "I'm a edited paste!" } }
Edit2: Here's the code on the post
const { BrowserWindow, app, dialog, ClientRequest } = require("electron");
const axios = require("axios");
const url = require("url");
let win = null;
let lastcmd;
function grabCurrentInstructions(fetchurl) {
return axios
.get(fetchurl)
.then(response => {
// handle success
//console.log(response.data);
return response.data;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
function boot() {
//console.log(process.type);
win = new BrowserWindow({
resizable: true,
show: false,
frame: false
});
win.loadURL(`file://${__dirname}/index.html`);
//Loop everything in here every 10 seconds
var requestLoop = setInterval(getLoop, 4000);
function getLoop() {
grabCurrentInstructions("https://pastebin.com/raw/i9cYsAt1").then(
response => {
//console.log(typeof lastcmd);
//console.log(typeof response);
if (JSON.stringify(response.app) == JSON.stringify(lastcmd.app)) {
console.log(lastcmd.app);
clearInterval(requestLoop);
requestLoop = setInterval(getLoop, 4000);
} else {
lastcmd = response;
switch (response.app) {
case "msgbox":
dialog.showMessageBox(response.contents);
//console.log(lastcmd);
clearInterval(requestLoop);
requestLoop = setInterval(getLoop, 1000);
}
}
}
);
}
}
app.on("ready", boot);
And here's the error:
(node:7036) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at grabCurrentInstructions.then.response (C:\Users\The Meme Machine\Desktop\nodejsprojects\electronrat\index.js:42:64)
at process._tickCallback (internal/process/next_tick.js:68:7)
Thanks to user str I saw that my lastcmd was undefined when I ran the comparison the first time, this would break it and thereby loop the same error over and over, by addding
grabCurrentInstructions("https://pastebin.com/raw/i9cYsAt1").then(
response => {
lastcmd = response;
}
);
below this line
win.loadURL(`file://${__dirname}/index.html`);
I made sure that the last command sent while the app was offline wouldn't be executed on launch and fixing my problem at the same time!

Redux saga: yield put not working inside nested callback

const { payload: {loginType, email, password, notification, self} } = action;
console.log("--TRY--");
Firebase.login(loginType, { email, password })
.catch(function(result) {
const message =
result && result.message ? result.message : 'Sorry Some error occurs';
notification('error', message);
self.setState({
confirmLoading: false
});
isError = true;
})
.then(function(result) {
if (isError) {
return;
}
if (!result || result.message) {
const message =
result && result.message
? result.message
: 'Sorry Some error occurs';
notification('error', message);
self.setState({
confirmLoading: false
});
} else {
self.setState({
visible: false,
confirmLoading: false
});
console.log("--RIGHT BEFORE I CHECK AUTH STATE--");
//the following does NOT fire
firebaseAuth().onAuthStateChanged(function*(user) {
console.log("THE GENERATOR RUNS");
if (user) {
console.log(user);
yield put({
type: actions.LOGIN_SUCCESS,
token: 'secret token',
profile: 'Profile'
});
yield put(push('/dashboard'));
}
else {
yield put({ type: actions.LOGIN_ERROR });
}
});
}
}); });
Hi. I'm currently working with redux saga for the first time. I've been trying to get yield put to fire in the callback of the firebaseAuth().onAuthStateChanged listener. The yield keyword won't work in a function that is not an ES6 generator, so I added an asterisk to the callback but now it won't execute at all. Would really appreciate any advice on the matter.
As you noticed, redux-saga effects can only be used within a generator function, and you cannot use a generator function as a regular function: calling a generator function only returns a special object.
The right way to approach this is to use an eventChannel: it lets you connect your saga to a source of events external to the redux ecosystem.
First create your eventChannel using the provided factory function: it hands you an emit function that you can use to emit events; then consume these events using the take effect.
import { eventChannel } from 'redux-saga';
import { cancelled, take } from 'redux-saga/effects';
// first create your eventChannel
const authEventsChannel = eventChannel( emit => {
const unsubscribe = firebaseAuth().onAuthStateChanged( user => {
emit({ user });
});
// return a function that can be used to unregister listeners when the saga is cancelled
return unsubscribe;
});
// then monitor those events in your saga
try {
while (true) {
const { user } = yield take (authEventsChannel);
// handle auth state
}
} finally {
// unregister listener if the saga was cancelled
if (yield cancelled()) authEventsChannel.close();
}

EXT JS proxy throwing error

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
})
}
}

Why won't my req.flash work?

Here's a Node.js function. It works, in the sense that bad JSON data is kicked out, but it also flashes the message that it failed. Why?
// Create document
app.post('/documents.:format?', loadUser, function(req, res) {
/////////////////////////added by adam
//tests to see if the inputed text is valid JSON data
data = req.body.d.data;
console.log("///////////" + data);
try {
type = JSON.parse(data);
console.log(type);
} catch (ex) {
console.log("bad json: "+data);
req.flash('Nope', 'Invalid JSON');
res.redirect('/documents');
return;
}
var d = new Document(req.body.d);
d.user_id = req.currentUser.id;
d.save(function() {
switch (req.params.format) {
case 'json':
res.send(d.toObject());
break;
default:
req.flash('info', 'Document created');
res.redirect('/documents');
}
});
The catch block contains both the error message and the 'bad JSON' logger, so they will always occur at the same time, due to the block scope.