Cant get attributes from error object - javascript

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?

Related

Jest test that simulates throwing an Axios exception fails with empty error message

I am trying to write a Jest test to cover a scenario whereby an axios.post (in the code I am trying to test) throws and handles an exception. The test successfully throws an error for a mocked axios instance and the appropriate catch block in the code I am wishing to test is reached. However, the error/exception message is empty. This then causes some assertions that I am trying to do in the test to fail.
The relevant section of the code to test looks as follows:
try {
// Call the token endpoint with the client/user credentials and check the response.
const { status, data } = axios.post(authenticationConfig.tokenEndpoint,
'grant_type=client_credentials', { headers });
if (status === StatusCodes.OK) {
...
}
}
catch(err) {
console.log(JSON.stringify(err));
res.status(StatusCodes.UNAUTHORIZED);
res.json(err.response.data.error);
}
The corresponding test looks like:
it('cannot get access token', async () => {
const response = {
response: {
data: {
error: 'My error'
}
}
};
const req = {
headers: {
'authorization': 'Basic client_id:client_secret'
}
};
mockedAxios.mockImplementation(() => {
throw new Error(response);
});
const provide = await authenticationMiddleware.provide(req, res, next);
await provide(req, res, next);
expect(mockedAxios).toBeCalledTimes(1);
expect(res.status).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
});
The err object in the catch block is logged out as an empty object even though from the test I'm throwing an error with a fully populated object. The test passes if I remove the 'res.json' statement from the catch block.
● authentication middleware › cannot get access token
TypeError: Cannot read property 'data' of undefined
89 | console.log(JSON.stringify(err));
90 | res.status(StatusCodes.UNAUTHORIZED);
> 91 | res.json(err.response.data.error);
Any ideas most welcome please. No doubt the way that I'm mocking Axios and causing it to throw an exception is wrong. The code does enter the catch block but the 'err' object is empty for some reason.
Many thanks.

I'm getting "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined" error in axios patch api

I am trying to update an array of objects using an Axios/Node.js API. I have successfully created the array, but when I try to pass in through an axios patch request, I am getting the "Cannot read property 'data' of undefined". Anyone know what I might be doing wrong?
My axios function is below:
export const updateTrans = async (transArr) => {
try {
const res = await axios({
method: 'PATCH',
url: `http://127.0.0.1:7000/api/v1/property/${id}`,
data: {
"transactions": transArr }
});
if (res.data.status === 'success') {
showAlert('success', 'Data updated successfully!');
}
} catch (err) {
console.log(err.response.data.message );
showAlert('error', err.response.data.message);
}
};
I have tried to stringify "transArr" as well, but still no luck.
The problem is that you're accessing err.response.data without checking if err.response exists. err.response is only present if the request was made and there was a response. If, for example, a CORS error or some network error occurred (or some other error inside the try block), it will not be present.
Just check that err.response exists before using it.
try {
// ...
} catch (err) {
console.log(err, err.response && err.response.data);
if (err.response && err.response.data) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
showAlert("error", err.response.data.message);
return;
}
showAlert("error", err.message);
}

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

object object with error handling in Angular

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

How to check function error using if/else statement?

I am creating session and sending traps to snmp devices, my code is working as expected and sending trap messages to host, Now below i have added validation to check if session has error while establishing connection, then throw error dont send trap message. So my question here is how can we execute function while checking if/esle condition and see if error exist in validateSession if error exist close session else send trap.
main.js
var session = snmp.createSession(host,"public",sessionOptions);
try {
function validateSession(){
session.on ("error", function (error) {
console.log (error);
session.close ();
});
};
if(!validateSession(){
session.trap(trapOid, varbinds, options, function (error) {
if (error)
console.log(error);
else
console.log('SNMP successfully delivered');
});
})
} catch (e) {
console.log("SNMP processing error: " + e);
}

Categories

Resources