Firebase push function is not working with sails post method - firebase

When I am hitting this function directly by URL it worked and this insert data in Firebase object
addCountry: function (req, res) {
var ref = db.ref();
var usersRef = ref.child("country");
usersRef.push({
name: 'United States',
is_deleted: 0,
});
return res.view('city-listing');
}
But when I called this function by the form submit post method then it will throw the error:
"error: Sending 500 ("Server Error") response:
Error: Can't set headers after they are sent."

Error: Can't set headers after they are sent.
Error occurs if you are sending the view more than once in the same route handler . It had happened to me once too. Check that you don't have more than one view related rendering which might execute twice.

Related

Accessing response error data in next.js using SWR

I have a form data which on submit I a sending to backend if there is an error I have process the error and show it on page. Request is getting posted fine but when getting a backend response I never go to catch error loop. Appreciate any help in resolving this.
Thanks
const [errorMessage, setErrorMessage] = useState('')
mutate(
`${api}`,
fetcher('POST', `${api`, body: JSON.stringify(data))
)
.then((data) => {
... do something
})
.catch((error) => {
setErrorMessage(data.error.message)
console.error(error)
})
}
backend response data :
{"trace_id":"abc","errors":[{"code":122,"message":" Error While
Submitting."}]}
The .catch clause will only fire if there is an error executing the network request. But in this case, it's working - it sends a request and gets a response. So only the then clause is fired. However, the response contains an error.
There are a few ways to make it so the error response gets 'caught' - either you configure your graphql library to look inside each response to check for 'errors' property to be non-empty and throw, or you can do that inside the then clause in your example.

How to access backend errors with Redux createAsyncThunk

I am not sure how I am supposed to get the errors that come from the backend when a POST request is sent to the backend. If I use plain axios calls, I can simply get the errors from the response object in the catch block with:
error.response.data.errors
But when using Redux and using createAsyncThunk method, on a 400 status code from the server, a rejected action is dispatched and the error object I get is a generic one like so:
{
message: "Request failed with status code 400"
name: "Error"
stack: "Error: Request failed with status code 400\n...."
}
How can I get the server errors, just like using axios?
You can make use of the rejectWithValue function from redux-toolkit to include the server error as the payload property of your rejected action.
It would be something like this (untested code because I’m on my phone)
const myAction = createAsyncThunk(
‘actionName’,
async ( arg, {rejectWithValue} ) => {
try {
const res = await axios.post(…);
return res.data;
} catch (error) {
return rejectWithValue( error.response.data.errors );
}
});
I think what you can do is add an additional check for the errors and also wrap the axios post request with a try catch block.
Note : In your case the request is failing so I guess there must be some error with the way you are making a request.

Meteor publication send custom sanitized error to client in publication

I am not sure if I am just doing something wrong or if this is actually not working. I want to display the original publication error on the client, in case I catched one:
Meteor.publish('somePub', function (args) {
const self = this
try {
// ... publication logic
catch (pubErr) {
self.error(pubErr)
}
})
On the client I am "catching" this error via the onStop callback:
Meteor.subscribe('somePub', args, {
onStop: function (e) {
// display e to user
}
})
However, while on the server the pubErr is a Meteor.Error and according to the documentation it should be sent to the client, the client just receives a generic sanitized error message:
on the server
{
stack: "useful stack of actual method calls",
error: "somePub.failed",
reason: "somePub.invalidArguments",
details: { arg: undefined }
}
on the client
{
stack: "long list of ddp-message calls",
isClientSafe: true,
error: 500,
reason: "Internal server error",
details: undefined,
message: "Internal server error [500]",
errorType: "Meteor.Error"
}
Note: I also tried to add the error to itself as sanitizedError field, as in the documentation mentioned, but no success either.
Am I missing something here?
Actually I found the answer to the issue after being pointed into the right direction.
The example code works fine on a new project, so I checked why not in my project and I found, that I did not surround the arguments validation using SimpleSchema by the try/catch (unfortunately my question was poorly designed as it missed this important fact, mainly because I abstracted away the schema validation from the publication creation):
Meteor.publish('somePub', function (args) {
pubSchema.validate(args) // throws on fail
const self = this
try {
// ... publication logic
catch (pubErr) {
self.error(pubErr)
}
})
So I thought this could not be the issue's source but here is the thing: Simple Schema is not a pure Meteor package but a NPM package and won't throw a Meteor.Error but a custom instance of Error, that actually has the same attributes (error, errorType, details) like a Meteor.Error, see this part of the source code of a validation context.
So in order to pass the correct information of a SimpleSchema validation error to the client you should
wrap it in a try/catch
add the isClientSafe flag to it
alternatively convert it to a Meteor.Error
Attach a custom Meteor.Error as sanitizedError property to it

Unit test Actions on Google Dialogflow locally

I'm trying to unit test a DialogflowApp locally by using the firebase shell environment. (in a cli do firebase experimental:functions:shell and then call my methods)
I have followed this guide by google https://firebase.google.com/docs/functions/local-emulator but they don't use the DialogflowApp where the invoked function tries to bind a request object containing intents and parameters like this ->
exports.myFunction = functions.https.onRequest((request, response) => {
const app = new App({ request, response });
function myMethod(app) {
let myArgument = app.getArgument(MY_ARGUMENT);
app.tell('Here we are responding');
}
let actionMap = new Map();
actionMap.set(MYMETHOD_ACTION, myMethod);
app.handleRequest(actionMap);
});
Regardless of what request object I send in the CLI, like this myFunction(require("../test/testdata.json")), the request body object is empty, like this body: {} which means I can't do app.handleRequest() or app.getArgument(). The error message I get is
RESPONSE RECEIVED FROM FUNCTION: 400, Action Error: no matching intent
handler for: null
I thought that if I populated testdata.json with the json request data shown in Actions on Google -> console.actions.google.com -> Simulator it would be valid data but no.
My question is, how can i mock my request data so that I can start unit testing my fullfillment methods locally?
EDIT 1:
firebase > myMethod.post("/").form(require("../test/testdata.json"))
Sent request to function.
firebase > info: User function triggered, starting execution
info: Function crashed
info: TypeError: Cannot destructure property `parameters` of 'undefined' or 'null'.
if we look in dialogflow_app.js we can see this code for fetching an argument value
getArgument (argName) {
debug('getArgument: argName=%s', argName);
if (!argName) {
error('Invalid argument name');
return null;
}
const { parameters } = this.body_.result;
if (parameters && parameters[argName]) {
return parameters[argName];
}
return this.getArgumentCommon(argName);
}
this.body_ is always just empty {}, regardless of how and what I send into the method when running locally.
EDIT 3
firebase > myMethod({method: "post",json: true, body: require("../test/testdata.json")})
Sent request to function.
firebase > info: User function triggered, starting execution
info: Function crashed
info: TypeError: Cannot destructure property parameters of 'undefined' or 'null'.
Invoking a Firebase HTTPS function using the shell requires a different form. It takes the parameters that the request module does, so in order to emulate a webhook, it will be something like this:
myfunction({
method: 'POST',
json: true,
body: require("../test/testdata.json")
});
These three parameters are important:
You need to specify that this is a POST operation
You need to indicate that the body will be JSON. This will send the correct header and won't try to send the body as x-www-form-urlencoded
You need to include the body. As an object is ok because you've set the json parameter to true.

With Backbone collection's "create", how do I check for errors in the backend?

When I do this:
Comments.create(dat, {
wait:true,
success:function(){
main_alert('Posted successfully', 'success', 3000);
},
error:function(????){
main_alert('Error posting', 'error', 'default');
}
});
I want my server to return an "error" whenever I notice something wrong no the backend. Currently, my server returns a JSON whenever the creation is complete. How does my server return an error? And what would the error argument be?
The parameters that both success and error receive are (model, response, options). Here is the reference. Under response there a property responseText with the text received from the server.

Resources