I'm trying to find out a way to print only the "message" part from my api call error but not sure how to get only that part so I would be really appreciated if I can get any suggestion or help.
So this is what it show me in the network tab when there is error in the api call (pic)
saveChartClick(err: any) {
// update the chart data here
if(!this.isTextChart && !this.isFigure && !this.isGrid){
this.chartService.updateChart(this.chart).pipe(takeUntil(this.death$)).subscribe((updated) => {
if(updated) {
this.chart = updated;
this.snackbar.open("Chart has been updated.", " ", {duration: 2500});
this.store.dispatch(updateChart({chart: this.chart}));
} else {
this.snackbar.open(err.message, "close ", { duration: 2500 });
}
}, err => {
this.snackbar.open(err.message, "close ", { duration: 2500 });
})
}
else{
// save the new data here
this.store.dispatch(saveChartData({ guid: this.chart.guid, data: this.chartData }));
}
}
Right now it showing me this, which is not what I want to display since it doesn't really tell what is the error.
Error Message it showing me right now (pic)
This is hard coded but this one example of what I want to display (pic)
The errors are handle in the backend and I can get different error message sometime so I don't want to hard code it.
In Angular's HttpErrorResponse object, this is how the message property looks like. What you want isn't
this.snackbar.open(err.message, "close ", { duration: 2500 });
but
this.snackbar.open(err.error.message, "close ", { duration: 2500 });
Or maybe, to be on the safe side (error can be null),
const errorMessage = err.error ? err.error.message : err.message;
this.snackbar.open(errorMessage, "close ", { duration: 2500 });
Related
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.
I am trying to use the nativescript-ocr plugin, and keep on getting this error message
CONSOLE ERROR file:///app/newcard/newcard.component.js:133:34: {
"error": "Recognize failed, check the log for possible details."
}
It is very unhelpful, and i have been stuck on it for too long.
Bellow you can see how i am implementing the ocr:
doRecognize(source: string): void {
console.log({source});
let img: ImageSource = new ImageSource()
img.fromResource(source).then((success: boolean) => {
if (success) {
this.ocr.retrieveText({
image: img,
language: 'eng',
onProgress: (percentage: number ) => {
console.log(`Decoding progress: ${percentage}%`);
}
}).then(
(result: RetrieveTextResult) => {
console.log(`Result: ${result.text}`);
},
(error) => {
})
}
});
}
The source string looks like so:
CONSOLE LOG file:///app/newcard/newcard.component.js:122:20: {
"source":
"file:///Users/georgekyr/Library/Developer/CoreSimulator/Devices/0723299A-7C8B-40C3-AE74- FEE8E08BB52D/data/Media/DCIM/100APPLE/IMG_0007.PNG"
}
Looking around, I find that there are cases wehere the folder app/tesseract/tessadata was created in the wrong way, so i have double checked that the folder exists in the right place with the right data in 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!
i have this function
searching() {
this._demoService.postData(this.url,this.searchtobesent).subscribe(
data =>{
this.listings=data;
this.errorMsg="";
if(data){
}
else{
this.errorMsg="Nothing Found";
}
},
error =>{
console.log("error : "+error);
this.errorMsg="Error Loading Your Listings";
}
) ;
}
When there are some results from my backend (that are being sent in Json format) everything is ok.
what i want is when the results are empty and i receive from the server this
[]
i want this.errorMsg to become Nothing Found.
Any help would be appreciated ;)
Thanks
Even it is an empty array, it is still a valid response.
You can use array.length to handle this.
if (data && data.length > 0) {
// do something
} else {
this.errorMsg = "Nothing Found";
}
I'm using NodeJS and an npm package called oauth to communicate with Twitter's search API. For some reason however, twitter is returning to me an empty array of statuses without any error... What is even more confusing is the fact that using a tool like Postman with the exact same request and keys returns the list of tweets? It makes no sense! Here is my request:
URL: https://api.twitter.com/1.1/search/tweets.json?count=100&q=hello&since_id=577103514154893312&max_id=577103544903462913
Here is my code:
var twitter_auth = new OAuth(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
config.consumer_key,
config.consumer_secret,
"1.0A",
null,
"HMAC-SHA1"
);
var request = twitter_auth.get(
"https://api.twitter.com/1.1/search/tweets.json" + url,
config.access_token,
config.access_token_secret
);
var chunk = "", message = "", that = this;
request.on("response", function(response){
response.setEncoding("utf8");
response.on("data", function(data){
chunk += data;
try {
message = JSON.parse(chunk);
} catch(e) {
return;
}
console.log(message);
if(message.statuses)
{
for(var i = 0; i < message.statuses.length; i++)
{
var tweet = message.statuses[i];
that.termData[term.name].push(tweet);
}
if(message.search_metadata.next_results)
{
that.openRequests.push(that.createNewSearch(message.search_metadata.next_results, term));
}
else
{
that.termCompleted(term);
}
}
else if(message)
{
console.log("Response does not appear to be valid.");
}
});
response.on("end", function(){
console.log("Search API End");
});
response.on("error", function(err){
console.log("Search API Error", err);
});
});
request.end();
The console.log(message) is returning this:
{
statuses: [],
search_metadata: {
completed_in: 0.007,
max_id: 577103544903462900,
max_id_str: '577103544903462913',
query: 'hello',
refresh_url: '?since_id=577103544903462913&q=hello&include_entities=1',
count: 100,
since_id: 577103514154893300,
since_id_str: '577103514154893312'
}
}
Any ideas what is going on? Why is the statuses array empty in my code but full of tweets in Postman?
This issue was described at twittercommunity.com.
Accordingly answer of user rchoi(Twitter Staff):
"Regarding web vs. API search, we're aware that the two return different results at the moment. We made upgrades to the web search. There is no timeline for those
changes to be brought to other parts of our system."
Try to use
https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
if you get empty result with api search functionality.
Please follow this link
https://twittercommunity.com/t/search-tweets-api-returned-empty-statuses-result-for-some-queries/12257/6