User Defined Exception is not working in JavaScript Promise - javascript

I implement user-defined exception in javascript code but it is not catching the exception.
I am providing my code :
function sendRequest(URL, Data, authorization, requestType,cuboidName) {
var Response = new $.Deferred();
var json;
if (requestType.toString() == "GET") {
$.ajax({
url: URL,
type: "GET",
dataType: "json",
headers: {
'Authorization': authorization,
'Accept': 'application/json'
},
success: function (result) {
Response.resolve(result);
//console.log("Response : " + JSON.stringify(result) + "\n\n\n");
},
error: function(err){
throw new Error("Error Code:\t"+err.status+"\nReason:\tCuboid Download failed for Cuboid:"+cuboidName);
}
});
}
return Response.promise();
}
I am calling the sendRequest function from the following code :
async loadDatatypeCuboid(dataCuboid)
{
try
{
dataTypeCuboiId = "444";
var res3 = new $.Deferred();
Utils.sendRequest(this.baseUrl+"rest/v1/grid/"+dataTypeCuboiId+"?importTid=-1&view=LATEST&mode=0&baselineId=-1", null, Globals.authorization, "GET","Datatype").then(function (result) {
res3.resolve(result);
if (result.status == 500) {
return;
}
else{
}
});
return res3.promise();
}
catch (error)
{
console.log(error);
}
}
I am not able to catch the thrown error. The console is showing as :
Utils.js:26 Uncaught Error: Error Code: 500 Reason: Cuboid Download
failed for Cuboid:Datatype
can anyone suggest How to Handle Exceptions in JavaScript Promise?
Thanks in Advance

Related

Calling sync ready made async ajax javascript function

I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.

Get the return value of a single function within Promise

I have the following snippet containing a Promise:
...
return Promise.all([postHTTP()])
.then(function (results) {
loginToken = results[0].data.token;
console.log("token:" + loginToken);
})
.catch(error => {
throw error;
});
...
And the function:
function postHTTP() {
request.post({
headers: { 'content-type': 'application/json' },
url: 'http://localhost:55934/api/Token',
body: { "email": "test#test.pt", "password": "test" },
json: true
}, function (error, response, body) {
if (error) {
throw error;
}
console.log("return test");
return body.token;
});
Altough the String "Return test" is printed, it gives me an error in the Promised above saying the following:
(node:15120) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'token' of undefined
Can anyone help me finding a solution or the problem source for this?
Thanks in advance,
Diogo Santos
The problem in your postHTTP function. When work with multi promise you have to pass array of promises into Promise.all, hence you function must look like this:
function postHTTP() {
return new Promise(function (resolve, reject) {
request.post({
headers: { 'content-type': 'application/json' },
url: 'http://localhost:55934/api/Token',
body: { "email": "test#test.pt", "password": "test" },
json: true
}, function (error, response, body) {
if (error) {
return reject(error);
}
console.log("return test");
return resolve(body.token);
});
});
}

How to return the response status

I have connections to the database written in Angularjs
$http({
url: '/api/v1.0/relations/status/' + angular.element('#username').val(),
method: "GET"
})
.then(function (result) {
...
})
.catch(function (error) {
if(error=== 403) {
$scope.divRelationship = false;
}
});
Try to retrieve the status code from the error, however, you cannot
angular.js:12587 GET http://localhost:8080/api/v1.0/relations/status/jonki97 403 ()
Receives such an error in the console. How can we remedy this?
The error object is actually a response object, which contains the property 'status'.
So your code would need to look like:
$http({
url: '/api/v1.0/relations/status/' + angular.element('#username').val(),
method: "GET"
})
.then(function (result) {
...
})
.catch(function (error) {
if(error.status === 403) {
$scope.divRelationship = false;
}
});
Source: https://docs.angularjs.org/api/ng/service/%24http#general-usage

Unhandled rejection error with Ajax Bluebird promise wrapper

I am trying to wrap Ajax into a Bluebird promise wrapper, but am receiving:
Error: Unhandled rejection (stack trace here...)
wrapper1.js
let fetch = require('./wrapper2');
function requestWeb(type, url, data) {
return new Promise(function(resolve, reject) {
url = config.serverUrl + url.trim();
let options = {
type: type,
data: data ? JSON.stringify(data) : null,
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
timeout: 15000,
xhrFields: { withCredentials: true }
};
fetch(url, options)
.then(data => {
resolve(data);
})
.catch(err => {
console.log('web api error: ' + err.message);
notify('Please check your interet connection');
reject(err);
});
});
}
wrapper2.js
import Promise from 'bluebird';
export default function(url, options) {
return new Promise(function(resolve, reject) {
$.ajax(url, options)
.done((result) => {
resolve(result);
})
.fail((xhr, err) => {
let proxy = new Error();
proxy.message = err || 'error is null';
proxy.name = 'ajax error';
reject(proxy);
});
});
}
Please note Bluebird requires different error object on reject().
I figured it out, BlueBird wants to warn you that a reject() call has been fired but you are not catching it. So I was using...
requestWeb(type, url, data).then((result)=>{});
So to fix, do one of two things: add the .catch() to the end of the call, or remove the reject(err) from the promise.

Translating a rest API call from angular to jQuery

Apologies if worded awkwardly, but I have to make an rest API call using jQuery. I've already made the call using angularJS before, but for this case I can't use that. I tried translating it to jQuery but I'm not getting the same results. Is there anything I'm doing wrong or am I missing information? I'm fairly new to jQuery so I feel as if I'm missing something crucial or misunderstood something.
Working code with angularJS:
var req = {
method: 'POST',
url: 'https://fakeurl.com/rest/v1/portal/user/' + $scope.email.value,
headers:{
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === '601') {
console.error('Token is invalid or has expired');
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error('Error calling rest endpoint',err);
reject();
});
} catch (ex) {
console.error('Exception calling rest endpoint',ex);
reject(ex);
}
});
};
My failing jQuery code:
var processCreate = function (email) {
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Try making an ajax call like this
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + 'glsFromWebsite';
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}

Categories

Resources