SequelizeDatabaseError: Sending the error in the response - javascript

Logging an error and sending it back in the response gives entirely different results even though it is the same variable!
adminservices.js
var updateAdminById = function(new_admin_data, callback) {
logger.info("new_admin_data: " + JSON.stringify(new_admin_data));
logger.info("new_admin_data.id: " + new_admin_data.id);
models.admin
// .update({ admin_password: passwordCypher }, { where: { id: admin_id } })
.update(new_admin_data, { where: { id:new_admin_data.id } })
.then(function(admin) {
callback({
Update: true,
admin
})
})
.catch(function(error) {
callback({
Update: false,
error
})
});
};
admin_routes.js
router.post("/updateAdminAccountById", function(req, res) {
adminService.updateAdminById(req.body, (updateData) => {
if (updateData.update) {
//Update is succesfull return updated admin data
res.status(200).json(updateData.admin)
} else {
//Update failed return error
logger.error(updateData.error);
res.status(400).json(updateData.error)
}
})
});
In the terminal, logging the error gives this:
2020-02-06T12:02:24+0100 admin_routes.js:459
SequelizeDatabaseError: invalid input value for enum enum_admins_role:
"Administrateur"
But, the response in POSTMAN is this:
{
"name": "SequelizeDatabaseError",
"parent": {
"name": "error",
"length": 179,
"severity": "ERROR",
"code": "22P02",
"file": "d:\\pginstaller_12.auto\\postgres.windows-x64\\src\\backend\\utils\\adt\\enum.c",
"line": "133",
"routine": "enum_in",
"sql": "UPDATE \"admins\" SET \"nom\"=$1,\"email\"=$2,\"mot_de_passe\"=$3,\"role\"=$4,\"id\"=$5,\"updatedAt\"=$6 WHERE \"id\" = $7",
"parameters": [
"NewUpdatedValue",
"NewEmail",
"NewPassword",
"Administrateur",
"29",
"2020-02-06 11:02:23.391 +00:00",
"29"
]
},
"original": {
"name": "error",
"length": 179,
"severity": "ERROR",
"code": "22P02",
"file": "d:\\pginstaller_12.auto\\postgres.windows-x64\\src\\backend\\utils\\adt\\enum.c",
"line": "133",
"routine": "enum_in",
"sql": "UPDATE \"admins\" SET \"nom\"=$1,\"email\"=$2,\"mot_de_passe\"=$3,\"role\"=$4,\"id\"=$5,\"updatedAt\"=$6 WHERE \"id\" = $7",
"parameters": [
"NewUpdatedValue",
"NewEmail",
"NewPassword",
"Administrateur",
"29",
"2020-02-06 11:02:23.391 +00:00",
"29"
]
},
"sql": "UPDATE \"admins\" SET \"nom\"=$1,\"email\"=$2,\"mot_de_passe\"=$3,\"role\"=$4,\"id\"=$5,\"updatedAt\"=$6 WHERE \"id\" = $7",
"parameters": [
"NewUpdatedValue",
"NewEmail",
"NewPassword",
"Administrateur",
"29",
"2020-02-06 11:02:23.391 +00:00",
"29"
]
}
My question is not why I am having this error. I have succesfully fixed it. My questions are:
How come the error is displayed differently in the terminal and in POSTMAN if it is the same variable?
Why doesn't the error description appear in POSTMAN like it appears in the terminal?

SequelizeDatabaseError is descendant of BaseError which in turn descendant of Error.
Error redefines .toString() to print instance's name and message properties like '${name}: ${message}' if both available.
For more details see:
https://sequelize.org/master/class/lib/errors/base-error.js~BaseError.html
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Error/toString

Related

How to parse Authorize.net payment response in Ionic / JavaScript?

I am getting a response from authorize.net payment gateway and tried many times and many ways to parse it but no luck.
Here is the main response from authorize.net:
"{"transactionResponse":{"responseCode":"1","authCode":"XXXXXX","avsResultCode":"Y","cvvResultCode":"P","cavvResultCode":"2","transId":"11111111111","refTransID":"","transHash":"","testRequest":"0","accountNumber":"XXXX0002","accountType":"AmericanExpress","messages":[{"code":"1","description":"This transaction has been approved."}],"transHashSha2":"2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4XXXX4BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B","SupplementalDataQualificationIndicator":0,"networkTransId":"HLH5UGDQFZ98LHRLDGIZEG7"},"messages":{"resultCode":"Ok","message":[{"code":"I00001","text":"Successful."}]}}"
I am following this tutorial.
I have tried this:
const result = JSON.parse(JSON.stringify(res.response));
console.log('1', result);
And result is:
1 {"transactionResponse":{"responseCode":"1","authCode":"9UQISS","avsResultCode":"Y","cvvResultCode":"P","cavvResultCode":"2","transId":"60164579108","refTransID":"","transHash":"","testRequest":"0","accountNumber":"XXXX0002","accountType":"AmericanExpress","messages":[{"code":"1","description":"This transaction has been approved."}],"transHashSha2":"2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4DA924BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B","SupplementalDataQualificationIndicator":0,"networkTransId":"HLH5UGDQFZ98LHRLDGIZEG7"},"messages":{"resultCode":"Ok","message":[{"code":"I00001","text":"Successful."}]}}
I want result like this:
{
"transactionResponse": {
"responseCode": "1",
"authCode": "XXXXXX",
"avsResultCode": "Y",
"cvvResultCode": "P",
"cavvResultCode": "2",
"transId": "11111111111",
"refTransID": "",
"transHash": "",
"testRequest": "0",
"accountNumber": "XXXX0002",
"accountType": "AmericanExpress",
"messages": [
{
"code": "1",
"description": "This transaction has been approved."
}
],
"transHashSha2": "2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4XXXX4BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B",
"SupplementalDataQualificationIndicator": 0,
"networkTransId": "HLH5UGDQFZ98LHRLDGIZEG7"
},
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00001",
"text": "Successful."
}
]
}
}
Please guide me...
This is the Answer to my question:
I am getting this data in res.response:
"{"transactionResponse":{"responseCode":"1","authCode":"XXXXXX","avsResultCode":"Y","cvvResultCode":"P","cavvResultCode":"2","transId":"11111111111","refTransID":"","transHash":"","testRequest":"0","accountNumber":"XXXX0002","accountType":"AmericanExpress","messages":[{"code":"1","description":"This transaction has been approved."}],"transHashSha2":"2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4XXXX4BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B","SupplementalDataQualificationIndicator":0,"networkTransId":"HLH5UGDQFZ98LHRLDGIZEG7"},"messages":{"resultCode":"Ok","message":[{"code":"I00001","text":"Successful."}]}}"
console.log('API', res);
var obj = eval("(" + res.response + ")");
console.log(obj);
I solve the problem so I thought I should have to post answers it may be helpful to others.

Issues adding sessions and information to the Google Fit REST Api using JS

So I am reasonably new to using API's with Js but I am struggling a lot to understand how the Google Fit API works. I am attempting to add a new Workout's data to the API by adding a session and some data for the intensity (heart points) of the session. I can get the session to appear correctly but run into constant errors when I try to create a dataSource and add a point to it for the session. It would be greatly appreciated if someone could help me to fix my code to achieve this or could direct me to a more thorough example of similar code as the API docs don't seem to be too well detailed with examples etc. Thanks in advance.
Here's the 3 api calls that I have written so far, one for creating the DataSource, one for the DataPoint and one for the Session. The session works correctly and adds a session of 1 hr for the correct activity but I am unable to get any of the other API requests to work.
Data Source :
``gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {"field":[{
"format": "floatPoint",
"name": "com.google.heart_minutes"
}],
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000019",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
``
Data Point :
``
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:292824132082:op:6:1000019",
"userId": "me",
"datasetId": "1592087806561000000-1592287806561000000",
"resource": {
"minStartTimeNs": "1592087806561000000",
"maxEndTimeNs": "1592287806561000000",
"dataSourceId": "raw:com.google.heart_minutes:292824132082:op:6:1000019",
"point": [
{
"startTimeNanos": "1592087806561000000",
"endTimeNanos": "1592287806561000000",
"value": [
{
"fpVal": 89.1
}
],
"dataTypeName": "com.google.heart_minutes"
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
``
Session :
``gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": "someSessionId19",
"id": "someSessionId19",
"name": "Awesome Workout19",
"description": "A very intense workout",
"startTimeMillis": new Date().getTime() - 3600000,
"endTimeMillis": new Date().getTime(),
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": 3600000
}).then((res) => {console.log(res)});
console.log('res')
//request.execute((res) => {console.log(res);console.log('executrd')})
console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
var request2 = gapi.client.fitness.users.sessions.list({
"userId":"me"
}).then((res) => {console.log(res)})
``
Error message
{message: "Unable to fetch DataSource for Dataset: raw:com.google.heart_minutes:292824132082:op:6:1000019", domain: "global", reason: "invalidArgument"}
It looks like it could be that you're trying to pass in the wrong fields for the data type: if you want to use a standard data type (like com.google.heart_minutes), you should either pass the exact fields of the standard data type (the field should be called "intensity"); or just pass the data type name, and the backend will fill them in for you.
So, if you change the data type to
"dataType": {"name": "com.google.heart_minutes"}
It should work.
Then, you need to use the data source ID returned from that request for the data points.
Awesome, so after some support in the comments I have some working code to add a new session with data from a previously defined data source using 3 API calls. The first call is to create a data source and only needs to be run once. The second and third then add a data point to a data set and creates a new session for the workout respectively. Here's the final working code:
Data Source:
/*
gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000020",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
*/
Data and Data Set:
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:108881196053:op:6:1000020",
"userId": "me",
"datasetId": z,
"resource": {
"minStartTimeNs": workoutStartTime * 1000000,
"maxEndTimeNs": workoutEndTime * 1000000,
"dataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"point": [
{
"originDataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"value": [
{
"fpVal": 8
}
],
"dataTypeName": "com.google.heart_minutes",
"endTimeNanos": workoutEndTime * 1000000,
"startTimeNanos": workoutStartTime * 1000000,
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
Session:
gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": id,
"id": id,
"name": "Morning Workout",
"description": "A very intense workout",
"startTimeMillis": workoutStartTime,
"endTimeMillis": workoutEndTime,
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": workoutEndTime - workoutStartTime
}).then((res) => {console.log(res)});
console.log('res')

How can I change the status code of App sync AWS?

That's the error data returned from App Sync AWS:
{
"data": {
"getContentById": null
},
"errors": [
{
"path": [
"getContentById"
],
"data": null,
"errorType": "Lambda:Handled",
"errorInfo": null,
"locations": [
{
"line": 1,
"column": 2,
"sourceName": null
}
],
"message": "ID is not found"
}
]
}
How can I change the 200 Status code from my lambda function?
Screen shot from PostMan
Currently you cannot customize the error status code in AWS AppSync. The suggested approach is to use errorType in the error response. You can use $util.appendError or $util.error methods in your velocity mapping template to define the error type.

Loopback: How can we modify the return data of a built in model function

I created a model named member inherited from the built in model User,
But how can I change the format of the login return. ie,
currently the invalid login is returning like
{
"error": {
"statusCode": 401,
"name": "Error",
"message": "login failed",
"code": "LOGIN_FAILED",
"stack": "Error: login failed\n ..."
}
}
I want to change like,
{
"code": 401,
"name": "Error",
"message": "login failed",
"code": "LOGIN_FAILED",
"stack": "Error: login failed\n ..."
}
Also, the success case as well,
ie current return is
{
"id": "P1jAavmCRbiYB1gYaE2snj3I6BayIYOCJ7HsTLeF1bezlEGVAUzjwdxKB5QFH9Vu",
"ttl": 1209600,
"created": "2017-02-02T13:19:05.709Z",
"userId": "5885b186db6df92d3ada7777"
}
I want to change like,
{
"code": 200,
"name": "Success",
"token": "P1jAavmCRbiYB1gYaE2snj3I6BayIYOCJ7HsTLeF1bezlEGVAUzjwdxKB5QFH9Vu",
"ttl": 1209600,
"created": "2017-02-02T13:19:05.709Z",
"userID": "5885b186db6df92d3ada7777"
}
Is it possible or not?
You need to remove strong-error-handler from middlewares and add your custom error handler like this
In config.json you need to do :
...
"remoting" {
...
"handleErrors": false
...
}
...
Also create config.local.js in root/sever folder and add below :
'use strict';
var errorConverter = require('./middlewares/error-converter');
module.exports = {
remoting: {
errorHandler: {
handler: errorConverter()
}
}
};
error-converter.js in middleare folder (or any other place) is the custom error hadnling middleare

Yammer JavaScript API erroneously throwing an error for an empty 200 response?

I am unable to post an activity from the Yammer JavaScript library. When I use yam.request the error callback is returned with an HTTP status code 200.
If I try to use yam.platform.request I get:
Origin https://3sharpepgdev03.sharepoint.com not found in Access-Control-Allow-Origin header. I have this path in my JavaScript origins list in Yammer.
Here is the code in case you see something else wrong:
<script>
function postActivity2() {
yam.request({
url: "activity.json",
method: "POST",
data: {
"activity": {
"actor": {
"name": "Jeff Kirkham",
"email": "garthf#retailv3dev2.onmicrosoft.com"
},
"action": "create",
"object": {
"url": "https://3sharpepgdev03.sharepoint.com/Pages/Yammer%20Test%20Page.aspx",
"title": "Lunch Meeting"
},
"message": "Hey, let’s get sushi!",
"users": [
{
"name": "Jeff Kirkham",
"email": "garthf#retailv3dev2.onmicrosoft.com"
}
]
}
},
success: function (msg) { alert("Post was Successful!: " + msg); },
error: function (msg) { console.dir(msg); }
})
}
</script>

Categories

Resources