I have made API on restify for my product. I have installed loggly and newrelic for monitoring purposes.
Recently newrelic notified me that there was an error somewhere in my code.
app.get('/myroute', (req, res, next) => {
let payload = { /*...*/ };
return new Promise((resolve, reject) => {
/* some code */
return resolve();
})
.then(/* some promise */)
.then(() => {
/* some code */
sendEmail({params}); // some error was thrown from one of the promise chain
// inside this function...
return something;
})
.then(/* some promise */)
.then(() => {
res.send(something);
})
.catch(next);
});
The promise chain resolved perfectly fine and user gets proper response, because I didn't return the sendEmail function. And I don't want to, because I don't want the user to wait for the response for long.
function sendMail(params) {
return new Promise((resolve, reject) => {
/* some code */
return resolve();
})
.then(() => {
params.abc.replace('a', 'b'); // error thrown, cannot find replace of undefined.
return something;
});
}
newrelic caught the error, but loggly didn't. I already have restify's formatters setup but it won't be enough as the request was successfully served and didn't fall into .catch(next).
I don't want a solution to fix the sendMail function. I just want to log if there is a bug like this.
Is there anyway to catch and log this type of error without putting a .catch() to sendMail function?
I figured out. I was trying process.on('uncaughtException') to handled it.
But I came across process.on('unhandledRejection') which did the job!
https://nodejs.org/api/process.html#process_event_unhandledrejection
Related
this is my router guard :
router.beforeEach(async (to,from,next)=>{
await store.dispatch('GetPermission');
if(to.matched.some(record => record.meta.requireAuth)){
let permissions=store.state.permissions; //getting empty
console.log(permissions);
if(permissions.filter(per => (per.name === 'read_list').length!=0)){
next({
path:'/dashboard/create'
})
}
else{
next()
}
}
// else if(to.matched.some(record => record.meta.requireAuth)){
// if(store.token!=null){
// next({
// path:'/dashboard'
// })
// }
// else{
// next()
// }
// }
else{
next()
}
});
problem is here though i m using await in dispatch method , i m not getting state value of permissions which is initially empty
here is vuex store code :
GetPermission(context){
axios.defaults.headers.common['Authorization']='Bearer ' + context.state.token
axios.get('http://127.0.0.1:8000/api/user').then((response)=>{
console.log(response)
context.commit('Permissions',response.data.permission)
})
//mutation:
Permissions(state,payload){
state.permissions=payload
}
//state
state:{
error:'',
token:localStorage.getItem('token') || null,
permissions:'',
success:'',
isLoggedin:'',
LoggedUser:{}
}
help me to solve it please ??
actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.
Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
Also,you are calling same route when no permission match, in that case it always call your same route and make infinite loop.
Redirect to access denied page if permission denied.
here is what i do, and i'am not realy sure its correct :
//store
async addUser({commit}) {
try {
const {data} = await apiService.addUser()
commit('SET_USER', data)
commit('SET_NOTIFICATION', {type:'success', message: 'user successfuly created'})
} catch (error) {
commit('SET_NOTIFICATION', {type:'error', message:error})
}
}
SET_USER(state, user) {
state.users.push(user)
}
//my component:
async addUser() {
this.isLoading = true
await this.$store.dispatch('updatePatient', this.form)
this.isLoading = false
}
is it legit ?
sometimes i think i would need more logic inside my component depending on the succes or rejected api request. Should i put all the logic in my actions ? like i do at the moment ?
Maybe should I add a status state for each actions, for example :
state {
users: []
postUserSuccess: null
postUserError: false
updateUserSuccess: null
updateUserError: false
// ...
}
and do what i want in the component with a computed property mapped to the store ?
What do you think ?
I don't know if it's a best practice but I let the components the exception handling. That method has its pros (you don't have to pollute the state with error management) and cons (you have to repeat the error management code for every action call).
All service calls will be made in actions
The state will only be set in mutations.
All service calls will return a promise with a resolve(data to load in the state) and a reject(message errors to present).
There will be an interceptor to reject the response in case there's a custom error (here you can put if the response has an error prop reject the response and send as an error the error prop, now you don't have to deconstruct the response in the action).
I'm going to give you a simplified example (I use axios, you can learn how to do it with the library that you use).
Actions in Vuex are asynchronous. So you don't need to try/catch them.
ApiService - Add User
const addUser = () => {
return new Promise((resolve, reject) => {
axios
.post(url, user)
.then(response => resolve(response.data))
.catch(error => reject(error));
});
};
store
async addUser({commit}) {
const data = await apiService.addUser();
commit('SET_USER', data);
return data;
}
if the promise in apiService.addUser is resolved the commit is going to be made if is rejected axios will return the promise and you can catch the error in the component that calls the action.
Component
async addUser() {
this.isLoading = true;
try {
await this.$store.dispatch('updatePatient', this.form);
} catch (error) {
// here goes the code to display the error or do x if there is an error,
// sometimes I store an errors array in the data of the component other times I do x logic
}
this.isLoading = false;
}
State
Your state will be cleaner now that you don't need to store those errors there.
state {
users: []
}
In my project, I use RxJS to handle HTTP request. I came into a confusing point about the error handling part as following:
.switchMap((evt: any) => {
return http.getComments(evt.params)
.map(data => ({ loading: false, data }))
.catch(() => {
console.log('debugging here');
return Observable.empty();
});
})
in the above code, inside the switchMap operator, I use the http.getComments function to send request, which is defined by myself as following:
getComments(params) {
return Observable.fromPromise(
this.io.get(path, { params })
);
}
in this function, I use fromPromise operator convert the returned Promise to observable.
The problem is when HTTP request failed, the catch operator inside switchMap can not work, the debugging console can't output. So what's wrong with my code.
Do you really need to catch the error inside the switchMap anyway? You can handle your error in your source if you want.
.switchMap((evt: any) =>
http.getComments(evt.params).map(data => ({ loading: false, data }))
})
.subscribe(console.log, console.error);
Any way, your source code does not look to have any error, maybe your promise is not been rejected when the http fails and is just resolving with an error as a response (this is a guess because I've seen that before)
Your code should work. Here a simplified simulation, where http calls are substituted by a function which raises an error.
import {Observable} from 'rxjs';
function getComments(params) {
return Observable.throw(params);
}
const params = 'abc';
Observable.of(null)
.switchMap(_ => {
return getComments(params)
.map(data => ({ loading: false, data }))
.catch(err => {
console.log('debugging here', err);
return Observable.empty();
});
})
.subscribe(
console.log,
error => console.error('This method is not called since the error is already caught', error),
() => console.log('DONE')
)
I am basically trying to wrap the React Native GPS feature into a Promise.
When I reach the failure callback of navigator.geolocation.getCurrentPosition I want to manually reject a Promise.
Here the relevant code:
var p = new Promise();
navigator.geolocation.getCurrentPosition(
(position) => { ... all good here ... },
(error) => {
// trying to reject manually a Promise
p.reject(error);
}
);
Problems:
If I don't pass any function in the Promise arguments I get not a function error on the first line
If I pass a function I get undefined is not a function evaluating p.reject
I was confusing Promise with an Angular-like deferred promise.
A working way is to wrap the GPS function into a Promise like so:
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(
(position) => {
resolve('All good');
},
(error) => {
reject(error);
}
);
});
I'm getting this error message with the snippet below
Unhandled rejection Error: reply interface called twice
Note that I'm using return for all the reply() interface
Locations
.findOne({
_id: request.params.id,
activationCode: payload.activationCode
}).then((location) => {
if (!location) {
return reply(Boom.notFound('Location not found'))
}
locationObject = location
if (payload.password !== payload.confirmPassword) {
return reply(Boom.badRequest('Password and Confirm Password must match'))
}
if (!payload.terms) {
return reply(Boom.badRequest('Must agree to Terms & Conditions'))
}
return newPaymentMethod.save()
}).then((paymentMethod) => {
.....
return user.save() // user is defined at .....
}).then(() => {
return reply({ token: helpers.createJwt(userObject) })
}).catch((err) => {
return reply(Boom.wrap(err))
})
Any help would be appreciated.
Looks like you get caught into this due to the incorrect use of promises. I guess you’re executing your snippet within a route handler where you’ve access to reply.
As you’re returning your responses within the promise chain, you both return the value to the next .then (promise) and also calling the reply from the outer scope.
I suggest you use a promise reject for errors so that you only need a single reply(Boom.method()) within the promise’s .catch().
Since you chain promises in the end
.then(() => {
return reply({ token: helpers.createJwt(userObject) })
}).catch((err) => {
return reply(Boom.wrap(err))
})
you might call reply twice if any of if conditions is true.
Easy solution would be to throw error in if condition is true - since there is already a Boom.wrap in catch block.