Loopback error without strong-error-handler - node.js

If I have strong-error-handler in my middleware.json (i.e "final": { "strong-error-handler": {} }) then the error response structure looks like this:
{
"error": {
"statusCode": 500,
"message": "Your Error Message",
"code": "123"
}
}
But when I remove strong-error-handler from middleware.json, then the error structure looks like this:
{
"errors": [
{
"status": 500,
"source": {},
"title": "Error",
"code": "123",
"detail": "Your Error Message"
}
]
}
I can't seem to figure out how/where that error body is made when I'm not using strong-error-handler. Is there a default?

Figured it out!! Turns out it was using the errorHandler from loopback-component-jsonapi node module.

Related

Azure REST API for running builds or pipelines

I am trying to automate the creation of Azure Pipelines for a particular branch using their REST api.
However, I am struggling to use almost all their API's, as their documentation lacks examples.
Things like List and Get are simple enough.
However, when it comes to queuing a build:
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-6.0
POST https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=6.0
{
"parameters": <parameters>, // how do i send paramters
"definition": {
"id": 1
},
"sourceBranch": "refs/heads/feature/my-pipeline",
"sourceVersion": "d265f01aeb4e677a25725f44f20ceb3ff1d7d767"
}
I am currently struggling to send parameters.
I have tried:
Simple JSON like:
"parameters": {
"appId": "bab",
"platform": "android",
"isDemo": true
}
and stringify version of JSON like:
"parameters": "{\"appId\": \"bab\",\"platform\": \"android\",\"isDemo\": true}"
but none seems to work.
It keeps giving me the error:
{
"$id": "1",
"customProperties": {
"ValidationResults": [
{
"result": "error",
"message": "A value for the 'appId' parameter must be provided."
},
{
"result": "error",
"message": "A value for the 'platform' parameter must be provided."
},
{
"result": "error",
"message": "A value for the 'isDemo' parameter must be provided."
}
]
},
"innerException": null,
"message": "Could not queue the build because there were validation errors or warnings.",
"typeName": "Microsoft.TeamFoundation.Build.WebApi.BuildRequestValidationFailedException, Microsoft.TeamFoundation.Build2.WebApi",
"typeKey": "BuildRequestValidationFailedException",
"errorCode": 0,
"eventId": 3000
}
The docs is very unclear in how to send this data: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-6.1#propertiescollection
Thank you very much for you help.
I believe you cannot pass runtime parameters trough the Queue API. Instead, use Runs API
With that, your request body (use Content-type: application/json) should look something similar to this:
{
"resources": {
"repositories": {
"self": {
"refName": "refs/heads/feature/my-pipeline"
}
}
},
"templateParameters": {
"appId": "bab"
"platform": "android"
"isDemo": true
}
}
I just realized that in the api-version=6.0 you can also send templateParameters on the Queue Service:
POST https://dev.azure.com/{organization}/{project}/_apis/build/builds?sourceBuildId={BUILD_BUILDID}&api-version=6.0
{
"templateParameters": { "doReleaseBuild": "True" },
"definition": {
"id": 1
},
"sourceBranch": "refs/heads/feature/my-pipeline",
"sourceVersion": "d265f01aeb4e677a25725f44f20ceb3ff1d7d767"
}

How to get all error with forEach function in the object directly?

Is it possible to get an array value from function if I put the forEach in the array?
Here is my code
res.status(400).send({
reason: err._message,
messages: Object.keys(err.errors).forEach((message) => {
return message; // I want messages will be arrays from err.errors
})
});
it doesn't return any error, and what I tried to achieve is the output like this
{
"reason": "some message from err._message",
"errors": {
"name": "Name field is required",
"etc": "etc field is required",
...
}
}
err.errors output (I don't want to show all the errors)
"errors": {
"name": {
"message": "Name field is required",
"name": "ValidatorError",
"properties": {
"message": "Name field is required",
"type": "required",
"path": "name",
"value": ""
},
"kind": "required",
"path": "name",
"value": ""
}
},
EDIT
as #jonrsharpe comment I tried using map
res.status(400).send({
reason: err._message,
errors: Object.values(err.errors).map((data) => {
return data.message;
})
});
it's already give me a correct value, but I don't know how to get the key
this code returns
{
"reason": "User validation failed",
"errors": [
"Name field is required",
"Email field is required"
]
}
But if possible I want the errors returns as Object
Please .reduce function from javascript.
Object.keys(err.errors).reduce((a,b)=>{
a[b]=x.errors[b]['message'];
return a
}, {})

Returning errors of Mongoose from Node.js

I get error from Mongoose in the following format
{
"errors": {
"companyName": {
"message": "Error, expected `companyName` to be unique. Value: `priStore`",
"name": "ValidatorError",
"properties": {
"type": "unique",
"message": "Error, expected `{PATH}` to be unique. Value: `{VALUE}`",
"path": "companyName",
"value": "priStore"
},
"kind": "unique",
"path": "companyName",
"value": "priStore",
"$isValidatorError": true
},
"companyEmail": {
"message": "Error, expected `companyEmail` to be unique. Value: `pri#gmail.com`",
"name": "ValidatorError",
"properties": {
"type": "unique",
"message": "Error, expected `{PATH}` to be unique. Value: `{VALUE}`",
"path": "companyEmail",
"value": "pri#gmail.com"
},
"kind": "unique",
"path": "companyEmail",
"value": "pri#gmail.com",
"$isValidatorError": true
}
},
"_message": "Client validation failed",
"message": "Client validation failed: companyName: Error, expected `companyName` to be unique. Value: `priStore`, companyEmail: Error, expected `companyEmail` to be unique. Value: `pri#gmail.com`",
"name": "ValidationError"
}
I need to show at the client in a good format like
Errors
Company Name already exist
Company Email already exist
Should I be parsing the error at my client end or Node.js end? At the Node.js end, I can return appropriate error messages which client can display to the user?
You could transform the errors object to an array of messages in Node.js by creating a helper method that takes the Mongoose error object, traverses the errors property and pushes error message to an array based on a pre-defined dictionary of error types and their messages.
The following function describes the above transformation and an example usage:
const handleError = err => {
const dict = {
'unique': "% already exists.",
'required': "%s is required.",
'min': "%s below minimum.",
'max': "%s above maximum.",
'enum': "%s is not an allowed value."
}
return Object.keys(err.errors).map(key => {
const props = err.errors[key].properties
return dict.hasOwnProperty(props.kind) ?
require('util').format(dict[props.kind], props.path) :
props.hasOwnProperty('message') ?
props.message : props.type
})
}
Example usage:
company.save(err => {
if (err) res.send({ errors: handleError(err) })
}

Gocardless - Redirect flow in Node JS

I'm trying to use Gocardless to enable SEPA payment in my website.
The example in the API doc doesn't work and seems uncomplete
POST https://api.gocardless.com/redirect_flows HTTP/1.1
{
"redirect_flows": {
"description": "Wine boxes",
"session_token": "SESS_wSs0uGYMISxzqOBq",
"success_redirect_url": "https://example.com/pay/confirm",
"prefilled_customer": {
"given_name": "Frank",
"family_name": "Osborne",
"email": "frank.osborne#acmeplc.com"
}
}
}
That's the response I get :
{
"error": {
"message": "not found",
"errors": [
{
"reason": "not_found",
"message": "not found"
}
],
"documentation_url": "https://developer.gocardless.com/api-reference#not_found",
"type": "invalid_api_usage",
"request_id": "7ae43821-345d-4ffd-98d6-15c4fe5513e6",
"code": 404
}
}
How can it work if the access token of the application is never asked for the request ?

Ionic Push Notification on database Insertion

Deal All,
I am working on Ionic2 which receives push notifications. It is working fine. I want to fo a step further. I need to automate the push notifications. I am using PHP with mySQL. I also have NodeJS WebApi. Is there any possibility in NodeJS or PHP to send Ionic Push notification? I have followed the following tutorial in NodeJS but I get 401 Unauthorized error:
ionic-push-server
Following is the error:
STATUS: 401
HEADERS: {"date":"Thu, 13 Apr 2017 19:13:09 GMT","content-type":"application/json; charset=utf-8","content-length":"196","connection":"close","server":"openresty","via":"1.1 vegur","access-control-allow-credentials":"true","access-control-allow-methods":"HEAD,GET,POST,PATCH,PUT,DELETE,OPTIONS","access-control-allow-headers":"DNT,Authorization,X-CSRFToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type"}
BODY: {"meta": {"version": "2.0.0-beta.0", "status": 401, "request_id": "00000000-1111-2222-3333-444444444444"}, "error": {"link": null, "type": "Unauthorized", "message": "JWT decode error occurred."}}
var ionicPushServer = require('ionic-push-server');
var credentials = {
IonicApplicationID : "IonicAppId",
IonicApplicationAPItoken : "IonicApplicationAPIToken" //You need to generate from app settings
};
var notification = {
"tokens": ["your", "device", "tokens"],
"profile": "AppProfileNameInSmallLetters",
"send_to_all": true,
"notification": {
"title": "Hi",
"message": "Hello world!",
"android": {
"title": "Hey",
"message": "Hello Android!",
"payload": {
"category": "Star"
}
},
"ios": {
"title": "Howdy",
"message": "Hello iOS!",
"payload": {
"category": "Star"
}
}
}
};
ionicPushServer(credentials, notification);

Resources