Handle 422 with $fetch - nuxtjs3

I'm upgrading a project to Nuxt3 and I'm using the new $fetch to hit my API, all it's OK but I can't manage the handle the 422 error from the API.
The API I've created would return something like this for the 422 code
{ message: "The email has already been taken.", errors: { email: ["The email has already been taken."]}}
Then in Nuxt I'm using this:
$fetch(`${runtimeConfig.public.BASE_API_BROWSER_URL}/XXX/`, {
method: 'POST',
body: {
...data
}
})
.then((resp) => {
message.value.push(resp.message)
isSubmitting.value = false
})
.catch((error) => {
errors.value.push(error.message)
isSubmitting.value = false
})
But what I have back is just FetchError: 422 Unprocessable Content instead of the error inside the API response, any idea on how to able to use error.message again?

Should be typically accessible via error.response.message.
For better visibility of the error object structure, use console.dir to explore its contents in the browser console: console.dir(error)
Unlike console.log(var1, var2, var3), console.dir only handles one attribute.
Important to remember this else you will be misled to thinking variables are empty.

Related

Is there a way to create a custom webhook using the REST API?

From the documentation, it says it is possible to create a custom web hook using the REST API, but no explanation has been provided.
My question is, has anyone ever created a custom web hook that did not send an error when setting up?
In my case I am trying to create a web hook that is triggered whenever a new product category is created:
const data = {
name: "Category created",
topic: "category.created",
delivery_url: "http://requestb.in/1g0sxmo1"
};
WooCommerce.post("webhooks", data)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error.response.data);
});
This request gives me an error. Other solutions exist but not using the REST API.

How to use Sign-In User ID to send push notifications

I have some users signed into my actions-on-google app via Google Sign-In ( https://developers.google.com/actions/identity/google-sign-in )
I want to sent push notifications to one of those users.
For getting push notifications work with actions in the first place, I tried this sample: https://github.com/actions-on-google/dialogflow-updates-nodejs/blob/master/functions/index.js but I only can get this to work without this commit: https://github.com/actions-on-google/dialogflow-updates-nodejs/commit/c655062047b49e372da37af32376bd06d837fc7f#diff-1e53ef2f51bd446c876676ba83d7c888
It works fine, but I think const userID = conv.user.id; returns the deprecated Anonymous User ID. The commit suggests to use const userID = conv.arguments.get('UPDATES_USER_ID'); which returns undefined.
I use this nodejs code to send the push notifications.
const request = require('request');
const {JWT} = require('google-auth-library');
const serviceAccount = require('./service-account.json');
let jwtClient = new JWT(
serviceAccount.client_email, null, serviceAccount.private_key,
['https://www.googleapis.com/auth/actions.fulfillment.conversation'],
null
);
jwtClient.authorize((authErr, tokens) => {
let notification = {
userNotification: {
title: process.argv[2],
},
target: {
userId: USERID,
intent: 'tell_latest_status',
// Expects a IETF BCP-47 language code (i.e. en-US)
locale: 'en-US'
},
};
request.post('https://actions.googleapis.com/v2/conversations:send', {
'auth': {
'bearer': tokens.access_token,
},
'json': true,
'body': {
'customPushMessage': notification, 'isInSandbox': true
},
}, (reqErr, httpResponse, body) => {
console.log(httpResponse.statusCode + ': ' + httpResponse.statusMessage);
});
});
I simply can't get this to work with the const userID = conv.arguments.get('UPDATES_USER_ID'); version, because as I said
When I use conv.user.profile.payload.sub as suggested here: https://developers.google.com/actions/identity/user-info the AoG API returns "SendToConversation response: Invalid user id for target."
Is there any way to make this work with Google Sign-In?
Has anyone made this work? I mean with the UPDATES_USER_ID field?
I already created an issue on the samples repo: https://github.com/actions-on-google/dialogflow-updates-nodejs/issues/15 but I was sent here.
Thanks!
While researching why I sometimes got undefined I found an answer on this question that solved my issue.
I've found solution for this problem. While getting UPDATES_USER_ID
conv.arguments.get() only works for first attempt. So, while building
your action you must save it. If you didn't store or save, you can
reset your profile and try again, you will be able to get.
You can reset your user profile for the action here.

Managing API calls with default error handling in react-redux application

I've completed my application and I'm now integrating the real api calls for each async action. I use redux-thunk which returns a promise from an axios instance.
Currently I'm repeating so much of the same logic in my actions that I'm sure I'm missing something.
API response example
{
"ok": true,
"warnings": [],
"errors": [],
"response": {/* stuff */}
}
The Idea is that I need the same error handling if either the axios call fails (so another response status then 2xx). Additionally I need to also do the same thing when the api response returns "ok": false.
Preferably I would like to dispatch an action which shows a notification to users so they also know when something goes wrong. Aside from that I want to log the api response's warnings and error entities. This is mainly because I'll use sentry for monitoring.
Any Ideas on how to do this without doing a .catch() with the same logic on each api call in any of my action creators?
I've thought about using the onError of axios but that can't dispatch an action as far as I know.
You could use a response interceptor to dispatch appropriate actions. Just wire them up after you create the store
const store = createStore(...)
axios.interceptors.response.use((response) => {
if (!response.data.ok) {
store.dispatch({ type: "RESPONSE_NOT_OK", response }
}
return response
}, (error) => {
store.dispatch({ type: "RESPONSE_HAD_ERROR", error }
return Promise.reject(error)
})
Obviously, you can handle the response how ever you want, this was just for demonstration purposes.

Angular 2 - Checking for server errors from subscribe

I feel like this scenario should be in the Angular 2 docs, but I can't find it anywhere.
Here's the scenario
submit a form (create object) that is invalid on the server
server returns a 400 bad request with errors I display on the form
after the subscribe comes back, I want to check an error variable or something (ie. if no errors > then route to newly created detail page)
I imagine it working something like this:
this.projectService.create(project)
.subscribe(
result => console.log(result),
error => {
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
I'm very new to Angular 2 so this may come from my lack of understanding in how an Observable works. I have no issue with displaying that data on the form, but can't figure out how to see it within the ts component. I really just want to check the success/fail of the http create.
As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.
For reference:
[onNext] (Function): Function to invoke for each element in the observable sequence.
[onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
[onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.
Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).
this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);
As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).
Rx.Observable.prototype.finally(action)
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
For instance, here is a basic example:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';
// ...
this.httpService.getRequest()
.finally(() => {
// Execute after graceful or exceptionally termination
console.log('Handle logging logic...');
})
.subscribe (
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// No errors, route to new page
}
);
Please note that the previous syntax with callbacks has been deprecated as of 6.4 and is going to be removed with 8.0. Instead of
of([1,2,3]).subscribe(
(v) => console.log(v),
(e) => console.error(e),
() => console.info('complete')
)
you should now use
of([1,2,3]).subscribe({
next: (v) => console.log(v),
error: (e) => console.error(e),
complete: () => console.info('complete')
})
https://rxjs.dev/deprecations/subscribe-arguments
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
Updated rxjs way 2022
this.projectService.create(project)
.subscribe({
next: (data)=>console.log('data',data),
error: (err)=>console.log('error',err),
complete:()=>console.log('complete')
});

Error while instanciating Restivus "Cannot find name 'Restivus' "

I imported restivus using :
meteor add nimble:restivus
And while using Restivus I encounter this error on meteor startup :
"Cannot find name 'Restivus' ".
I can although GET requests but I wonder if it impacts the behavior of the app.
Here is the code used :
if (Meteor.isServer) {
// Global API configuration
var Api = new Restivus({
apiPath: 'api/',
prettyJson: true
});
}
When receiving POSTs my request.body and my bodyParams are empty :
Api.addRoute(':id/test', {
post: function () {
var id = this.urlParams.id;
console.log("Body contains : ");
console.log(this.bodyParams);
return {
status: 'success',
url : 'post test from id: '+id,
body : this.bodyParams
};
}
});
Does anyone know how to make this error disappear and if this is linked to the POST body problem ?
If you use Meteor 1.4+ you can try to import Restivus to your file with something like this:
import Restivus from 'nibmle:restivus';
The problem with post body being empty was caused by the request I made :
I wasn't specifying the Content-type header.
Once I specified the "Content-Type": "application/json" it worked.
The "Cannot find 'Restivus' " Error is still here though.
Your code looks ok. Here is some code from a server-only file that I am using:
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true,
apiPath: 'restAPI/',
defaultHeaders: { 'Content-Type': 'application/json;encoding="UTF-8"' }
});
// Generates: GET, POST on /api/items and GET, PUT, DELETE on
// /api/items/:id for the Items collection
Api.addCollection(Policy);
Perhaps you should move your code to the server directory? I am on Meteor 1.3.4.

Resources