I have strange error generation function.. It is from HttpRequest like this
public async request(method, url, data, headers = {}){
let init { method: method };
if (data) {
let payload: string = JSON.stringify(data);
init.body = payload;
}
if (this.key) headers["x-auth-token"] = this.key;
headers["Content-Type"] = "application/json";
init.headers = headers;
let result = await fetch(url, init);
if (result.status == 200) return result;
throw { status: result.status, message: result.statusText };
}
Now, I am trying to catch with something like this:
try {
let img = await HttpRequest.request("GET", "/login");
let text = await img.text();
let str = "data:image/jpeg;base64, " + text;
this.setState({ avatar: str });
} catch (err) {
console.log("log here");
}
What is strange, was that nothing catched, even though I deliberately made an error, no "log here" shows anywhere in console.
But if I change it like this:
try {
let img = await HttpRequest.request("GET", "/login");
let text = await img.text();
let str = "data:image/jpeg;base64, " + text;
this.setState({ avatar: str });
} catch (err) {
console.error("log here"); // <--- console.error() instead of console.log
}
Then the console showed "log here" error. It is strange that difference between console.log and console.error inside same catch clause treated different way.
Can anyone help me here, where did I do wrong?
Thank you
EDIT: If it made difference, the code behaved correctly before, when I throw the error as throw "ERROR " + result.status + ": " + result.statusText; at my request() function. It was back to normal when I changed it back to throw string instead of object.
Well.. I am not sure if this is the answer, or proper answer, but the question turned out not programming or javascript nature.
After I tried Parth Savaliya's comment, I had some ideas, and I tried to make this very simple function
function testError() {
throw {aa: 'test', bb: 'bb'};
}
try {
console.log("nothing here");
testError();
} catch (err) {
console.log(err);
console.log('foo');
}
and every time I feed different object, any console command, including console.error() gave me different result. The previous console.error() was just luck. It was varying from unintelligible mumble jumble, various strings, to no output, and finally crashed Google Chrome. There was no pattern, and seemed random. I also tried to replace console.log() in catch clause with an XHR request to server, and it worked fine. Firefox worked fine. So I conclude that it was chrome's console that was having problem. Tried to remove all extensions, cleaned cache and everything, reinstall chrome, and it was solved.
I think you're currently viewing only error logs, like
this...!
Please click on the first item on the list, to show all types of log, like
this...!
Related
bot.on('message', async msg => {
let args = msg.content.split(" ");
if(!msg.guild) return;
if(msg.author.bot) return;
if (msg.content === '<prefix>') {
const req = await GuildModel.findOne({ id: msg.guild.id });
if (!req) return msg.reply('Sorry! doc doesnt exist.');
return msg.reply(`Found a document! Prefix: ${req.prefix} Suffix: ${req.suffix}`);
}else if(msg.content.includes(`<setprefix>`)) {
const req = await GuildModel.findOne({ id: msg.guild.id });
if(!req) return msg.reply('Sorry there was an error!');
await GuildModel.findOneAndUpdate({ id: msg.guild.id }, { $set: { suffix: `${args[1]}`}}, { new: true})};
return msg.channel.send('Your new prefix is asdasd')
})
So essentially my problem is that when I test the bot any message sent in any server the bot is in is responded with Your new prefix is asdasd Ive tried to troubleshoot but Ive hit my limit and cant figure it out. Im using discord.js and have received no errors in my console! Thanks for any help!
If you indented your code more consistently you would immediately notice that your curly braces must be mismatched, because the } on the last line can not both close the elseif block and the async msg => { block.
The reason your code compiles is that the elseif block is ended by an extra } on the line await GuildModel.findOneAndUpdate(...)};, so return msg.channel.send(...) is outside the if statement, and always executed.
To avoid such errors, be mindful to always indent your code consistently (one brace per indent level). Also, try to avoid writing lines that are so long and convoluted that an extra } is not noticed.
I suspect threadabortexception issue of .NET but I couldn't fix it with possible options.
In short Redirect function throws an errors and goes to the catch, no matter to set the second parameter true or false).
The code below is just an example (but I faced this a couple of times before in real-time projects).
...
try {
var TSD = TriggeredSend.Init("DE_Name");
var Status = TSD.Send(data.subscriber, data.attributes);
if (Status != "OK") {
Platform.Response.Redirect(Variable.GetValue("#error_page"));
} else {
Platform.Response.Redirect(Variable.GetValue("#thanks_page")); //<<<-- This redirect throw error
}
} catch (err) {
Platform.Response.Redirect(Variable.GetValue("#error_page")); // <---- here it comes
}
...
Resources might helps:
1# https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end-response-redir
2# https://developer.salesforce.com/docs/atlas.en-us.mc-programmatic-content.meta/mc-programmatic-content/ssjs_platformClientBrowserRedirect.htm?search_text=Redirect
Any workaround is welcome.
I know this is an older question but I think it would be good to share findings.
There is no logical explanation to me why this is happen but the Redirect always throws an error and if it is used in a try block, the catch part will be executed.
Here is a simple workaround:
...
try {
var TSD = TriggeredSend.Init("DE_Name");
var Status = TSD.Send(data.subscriber, data.attributes);
try {
if (Status != "OK") {
Platform.Response.Redirect(Variable.GetValue("#error_page"));
} else {
Platform.Response.Redirect(Variable.GetValue("#thanks_page")); //<<<-- This redirect throw error
}
} catch(e) {}
} catch (err) {
Platform.Response.Redirect(Variable.GetValue("#error_page")); // <---- here it comes
}
...
I am trying to bring an array of strings from a database to a dropdown menu on a website I have created. I have everything working properly except for the final transfer of the data from the retrieval method to the website. Right now the data is in the form of a Promise, and I cannot for the life of me figure out how to get it to print out on my webpage. right now I'm just sending it to localhost:3000, I'm not at the point where I'm putting it into the dropdown yet. How would I do this ?
I've found very very little on this issue online and thus have been mainly just trying hack fixes that haven't really worked (tacking on the resolve() method, all() method). both of those resulted in syntax errors. All Var names/SQL queries have been changed btw. My latest attempt is below:
//code that sends the names to the webpage
app.get('/formfetch', function(req, res) {
const data = async() => {
let rawDat = await dbFormFetch.getNames();
return rawDat;
}
}
const hNs = data();
hNs.then((names) => {
if (names === null) {
res.end("Error: Names list came through as null.");
} else if (names.length > 0) {
resolve(names);
for (var i = 0; i < names.length; i++) {
res.end(names[i]);
}
res.status('200');
}
})
.catch((err) => {
res.status('404').json(err)
console.log("conversion of promise failed")
})
});
//the getNames() method (in a different file)
async function getNames() {
console.log("trying to get Names");
let query = `select NAME from NAMESTAB`;
console.log("query: " + query);
const binds = {};
const result = await database.simpleExecute(query, binds);
var results = [];
console.log("for loop in formfetch.js: ");
for (var i = 0; i < result.rows.length; i++) {
results[i] = i + ": " + result.rows[i].NAME+ ' \n';
}
return results;
}
The res.send method from the app.get function prints out "Made it to the Web server:" on my localhost. I checked the console, and I didn't see anything hidden in the html or something like that.
**Note: all of the data that should be in the promise is in the code (I can print it to console at any point in the code), but when I put it on the website it won't print. **
so big surprise here, I was doing it all wrong. Lesson of the day: read up on Promises and how they work before running and gunning your way through some async code. It's not as intuitive as you would hope.
// I only had made changes to the first of the two methods.
app.get('/formfetch', function(req, res) {
async function data() {
let rawDat = await dbFormFetch.getNames();
return rawDat;
}
data().then((Names) => {
if (Names === undefined) {
res.end("Error: Names list came through as null.");
} else if (Names.length > 0) {
res.setHeader('Content-Type', 'application/json');
res.status(200).json({ "names": Names });
}
})
.catch((err) => {
res.status('404').send("name retrieval failed in server.js module")
console.log(err)
console.log("conversion of promise failed")
})
});
when you use res.end() , it sets the header status and renders it immutable after calling this method, so it was the wrong thing to use. Instead of this, I used the setHeader() method to tell the website what kind of information I'm sending it, and then filled in the content by chaining the .json() method to the status() response I sent. I've never worked with promises before and I'm fairly new to NodeJS so this was a bit of a learning curve, but hopefully this helps people who are where I was yesterday. if you're new to promises, see this article and this article before you try to use this coding tool. you'll save yourself hours of debugging and error tracing.
The promise that is returned by userRef.remove() is not giving any error, it always goes to then block even though if I change the non existing path dbRef.child('userssafasfsadf/' + userID); like so.
function deleteButtonClicked(e) {
e.stopPropagation();
var userID = e.target.getAttribute("userid");
const userRef = dbRef.child('users/' + userID);
userRef.remove()
.then(() => {
console.log('success!, show alert now');
})
.catch(err => {
console.log('errorcode', err.code);
});
}
Any help would be appreciated. Thanks.
It sounds like you're expecting the remove() function to generate an error if there was no data at the given location. It doesn't work that way, because the remove() is not transactional. Someone else could have removed the data a split second ahead of you, and that's OK. Database operations only return errors when a security rule is violated.
Useage of 'request-native-promise' not correctly chaining to it's subsequent 'then' and 'catch' handlers.
My Protractor Test
// There's a bunch of other imports here
import { browser } from "protractor";
const RequestPromise = require('request-promise-native');
describe('spec mapper app', () => {
let specMapperPage: SpecMapperPage;
let specMapperFVRPage: SpecMapperFieldsValuesReviewPage;
let loginLogoutWorkflow: LoginLogoutWorkflow;
let apiToken: LoginToken;
let tokenUtil: TokenUtil;
let projectRecordsToBeDeleted = [];
let requestHandler;
let logger = new CustomLogger("spec mapper app");
let speccyEndpoints = new SpeccyEndpoints();
beforeAll( () => {
logger.debug("Before All")
loginLogoutWorkflow = new LoginLogoutWorkflow();
loginLogoutWorkflow.login();
tokenUtil = new TokenUtil();
tokenUtil.getToken().then((token:LoginToken) => {
apiToken = token;
requestHandler = new SpeccyRequestHandler(apiToken);
});
});
describe('import/export page', () => {
it('TC2962: I'm a test case', () => {
let testLogger = new CustomLogger("TC2955");
// Test Var setup
... // removed for brevity
// Test Setup
browser.waitForAngularEnabled(false);
// Setup the record to be on the mapper page
let body = speccyEndpoints.generateRevitPostBody(PROJECT_ID, fileName);
requestHandler.postToSpeccy(speccyEndpoints.DELITE_REVIT_POST_URI, body).then((response) => { // EDIT: removed non-existant argument "rejection"
// --> The then handler the promise is STILL not resolving into
// Only made it here like once
console.log("Response is: ");
console.log(response);
// I got this to work once, but now it's not
console.log("Response body is: ");
console.log(response.body);
}).catch(error => {
// --> The catch handler is ALSO NOT resolving
console.log("catch handler executed!");
console.log(error);
});
});
});
});
The test case where things are going wrong. My console.log("Response is: "); is NOT being outputted. I'm not getting error messages as to why.
My Speccy Request Handler Wrapper Class
import * as RequestPromise from "request-promise-native";
import {LoginToken} from "../testObjects/LoginToken";
import {CustomLogger} from "../logging/CustomLogger";
export class SpeccyRequestHandler {
_baseAPIURL = 'http://myapi.net/';
_options = {
method: '',
uri: '',
auth: {
'bearer': ''
},
headers: {
'User-Agent': 'client'
},
"resolveWithFullResponse": true,
body: {},
json: true
};
_logger;
constructor(apiToken: LoginToken) {
this._options.auth.bearer = apiToken.idToken;
this._logger = new CustomLogger(SpeccyRequestHandler.name);
}
getOptions() {
return this._options;
}
postToSpeccy(uri:string, body?) {
this._options.method = 'POST';
this._options.uri = this._baseAPIURL + uri;
if(body) {
this._options.body = body;
}
return RequestPromise(this._options);
}
getFromSpeccy(uri) {
this._options.method = 'GET';
this._options.uri = this._baseAPIURL + uri;
return RequestPromise(this._options);
}
}
This is my Request Handler specific to one of my APIs, the Speccy one, and has some custom aspects to it in the URL and the token passing.
Sources
Request-Promise-Native Github Page
Request-Promise Github page, documentation location
Update Number 1
After the fix #tomalak brought to my attention, my console.log's in the .then(... handler were being executed, the first 5-ish times after I changed over to this, I was getting a roughly 150+ line console log of the response object that contained a body of response I would expect from my request URI. I even got the body out by using response.body. I thought things were fixed and I wasn't using my logger that logs out to file, so I lost my proof. Now when I run this test and this request I do not go into the .then(... handler at all. I'm also not going into the catch. My request is working though, as my resource is created when the post endpoint is hit. Any further suggestions are appreciated.
What would cause something to work sometimes and not others? My only thought is maybe the generic post name in my request handler wasn't being used in lieu of another method higher up the build chain being caught.
Update Number 2
Removed a bunch of stuff to shorten my question. If you need more clarification, ask and I'll add it.
It ended up being a timeout on the end of the API. My response was simply taking too long to get back to me. It wasn't failing, so it never went into the catch. And I had it working at one point because the response taking so long is due to an overabundance of a certain resource in our system in particular. I thought it was me and something I had written wrong. Long story short, suspect your system, even if you think it's perfect or if your devs swear up and down nothing could be broken.
Also, the request-debug module was a nice thing to have to prove that other endpoints, such as the rest testing endpoints at https://jsonplaceholder.typicode.com/ , do work with your code.