object object with error handling in Angular - javascript

So I followed the error handling guide in the angular docs. I always seem to receive the error in my service, however, my console always displays my error object as '[object Object]'. Does anyone know what causes this and how I can fix this?
My service file
subViewPlus(section, sign){
return this.http.get('http://localhost:3000/forum/subViewPlus/' + section + '/' + sign)
.pipe(catchError(this.handleError)
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an ErrorObservable with a user-facing error message
return new ErrorObservable(
'Something bad happened; please try again later.');
};
Screenshot that shows the logs to the console: how do I transform this [body body] into something more useful?

dont do interpolation on the object. Instead do something like this.
console.error({
"Backend returned code: ": error.status,
"body was: ": error.error
})

Related

Request with javascript Fetch API returns "object error"

I am trying to learn how to request JSON data with the javascript Fetch-API to fetch data from an open data portal called CKAN
Following the google documentation I tried this code:
fetch('https://ckan.open.nrw.de/api/3/action/package_list')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
This function catches an object Error (when opening the URL in my browser, I get a valid JSON):
"Fetch Error :-S", [object Error] { ... }
What is the probleme here?
Here is a working jsfiddle
Thanks for your help!

Pino error log is empty, although error object contains information

I have written a small error handling function, which is invoked after an AXIOS request, like so:
try {
...
} catch (error) {
handleAxiosError(error);
}
The function is as follows:
function handleAxiosError(error) {
if (error.response !== undefined) {
logger.error(`Received a HTTP error. Status code: ${error.response.status}, Data: ${error.response.data}`);
} else if (error.request !== undefined) {
logger.error(error.request);
} else {
logger.error(error.message);
}
throw new Error(error);
}
Although an error is thrown:
(node:94324) UnhandledPromiseRejectionWarning: Error: Error: connect ECONNREFUSED 127.0.0.1:6557
at handleAxiosError (C:\pathtoapp\utils\utils.js:66:11)
Pino only saves the following to the log. I can't find the problem. Is this an async issue?
{"level":50,"time":1567435455281,"pid":94324,"hostname":"host","name":"app","res":{},"v":1}
Thanks!
When using async logging (the default for the Pino logger), the process might have exited before all of the logging has been processed.
See https://github.com/pinojs/pino/blob/HEAD/docs/asynchronous.md
You can also change the logging to be synchronous, and you won't have this problem:
const dest = pino.destination({ sync: true })

generic throw giving Expected an object to be thrown lint error

Below throw code giving lint error Expected an object to be thrown no-throw-literal
throw { code : 403, message : myMessage };
if i try throw new Error, i am not getting eslint but it gives [Object Object] in the response.
throw new Error({ code : 403, message : myMessage });
Could someone tell me how to fix Expected an object to be thrown error ? without removing eslint config/rules
throw Object.assign(
new Error(myMessage),
{ code: 402 }
);
Throw a regular error and extend it with custom fields.
You could also write a reusable error class for that:
class CodeError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
throw new CodeError(myMessage, 404);
That way, you can distinguish the errors easily on catching:
} catch(error) {
if(error instanceof CodeError) {
console.log(error.code);
} else {
//...
}
}
Another simple workaround is store on variable and throw.
const errorMessage = { code : 403, message : myMessage };
throw errorMessage;

Angular 5 HttpClient Error response not catchable

We're working with Angular 5 and a Spring 2 OAuth Backend.
Now when I send an old token it's of course expired. It returns status code: 401 and an error response with invalid token and so on. Now I can't see it in my logs or when I catch the error. I want to get the error so I can at first log it and later on either refresh the token or send him to the Login Page.
Now if i subscribe to the request with:
.subscribe(res => {
//just random stuff.
}, err => {
console.log("error", err);
});
I just see this response in the log with an unknown error like in this image
Could it be failure of the backend? Because i also see in the logs something like a "No 'Access-Control-Allow-Origin' header is present"-error, although it's because of the invalid token.
Although I can see this response code in Google Chrome Dev Tools
and a 401 status code.
So I tried to find a solution myself. I've already got an interceptor and tried it with some solutions
return next.handle(authReq)
.catch(error => {
console.log("im in here");
console.log(error);
return Observable.throw(error);
});
The Http Service just throws an error that catch is not a function without even logging the error or the "im in here".
I have also tried with the .do after next.handle and I got the same error like catch
.do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
console.log(err);
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
}
}
});
I've tried with pipe after the http.get but it doesn't work either.
http.get(...).pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
import 'rxjs/add/operator/catch';
Somefunc(){
this.httpClient
.get("data-url")
.subscribe(
data => console.log('success', data),
error => console.log('oops', error)
);
}
OR
this.httpClient
.get("data-url")
.catch((err: HttpErrorResponse) => {
// simple logging, but you can do a lot more, see below
console.error('An error occurred:', err.error);
});
Should work.

Cant get attributes from error object

I am connecting to the Facebook API and I receive this error
{ [Error: failed [500] {"error":{"message":"Invalid parameter","type":"FacebookApiException","code":100,"error_subcode":1349125,"is_transient":false,"error_user_title":"Missing Message Or Attachment","error_user_msg":"Missing message or attachment."}}] stack: [Getter] }
I want to receive the error_user_msg
try {
var response = Social.createPosting(graphType, data);
} catch (exception) {
console.log(exception)
throw new Meteor.Error(exception.error_user_msg)
}
Problem is only message attribute is defined on the Error object that is returned.
exception.message returns
failed [500] {"error":{"message":"Invalid parameter","type":"FacebookApiException","code":100,"error_subcode":1349125,"is_transient":false,"error_user_title":"Missing Message Or Attachment","error_user_msg":"Missing message or attachment."}}
Which is a String, but is not valid JSON, so I cannot parse it either
What am I missing?

Categories

Resources