How to check unwrapError - mithril.js

var users = m.request({
method: "GET",
url: "hoge.json",
unwrapSuccess: function(response) {
return response;
},
unwrapError: function(response) {
//return response.error;
return "404 error";
}
});
users.then(function(result) {
console.log(result);
});
After delete "hoge.json".
I want to catch "404 error",but
uncaught SyntaxError: Unexpected token <
2016/2/18 add
I want to test alert ("unwrapError");
Below code is always alert ("unwrapSuccess");
How to change below code?
What is the unwrapError?
▼js
var users = m.request({
method: "GET",
url: "hoge.json",
unwrapSuccess: function(response) {
alert ("unwrapSuccess");
return response;
},
unwrapError: function(response) {
alert ("unwrapError");
return "error";
}
});
users.then(function(result) {
console.log(result);
});
▼hoge.json
[{"name": "John"}, {"name": "Mary"}]

If you take a look at mithril's source code you will see that m.request is just a wrapper for the XMLHttpRequest API. And that's what happens when the request's readyState attribute changes:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
options.onload({type: "load", target: xhr})
} else {
options.onerror({type: "error", target: xhr})
}
}
}
So mithril's unwrapError callback will be called whenever the response status is not a 2xx.
I updated the fiddle calling a URL that returns a 500 response and now the unwrapError is called.

Related

Handling errors on nuxt3 usefetch

I just cant figure out how to handle errors here:
const { error, data } = useFetch('https://example.app/api/contact', {
method: "POST",
headers: { "Content-Type": "application/json" },
body: {
name: form.name.value,
email: form.email.value,
message: form.message.value
}
});
console.log(error.value, error)
On error itself it returns ref with _error that contains object with errors. However I cannot get to those errors anyhow..
ref: https://v3.nuxtjs.org/api/composables/use-fetch
useFetch return values {data, pending, error, refresh}, here is an example.
const { data, pending, error, refresh } = await useFetch(
'https://api.nuxtjs.dev/mountains',
{
pick: ['title']
}
)
BTW,useFetch return a Promise, in your example, you can do as follows.
useFetch('https://example.app/api/contact', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: {
name: form.name.value,
email: form.email.value,
message: form.message.value
}
}).then(res => {
const data = res.data.value
const error = res.error.value
if (error) {
// dealing error
console.log(error)
} else {
console.log(data)
}
}, error => {
console.log('exception...')
console.log(error)
})
Ok, here is a practical solution, you can do the console log after checking error, like this:
if (error.value) {
console.log(error.value)
throw createError({statusCode: 404, statusMessage: "Page
not found.", fatal: true})
}
You do not get error out, why console.log fails, you need to get the value after the error is trigged.

How to read the response returned to a Twilio function from another function?

Really basic question - I'm calling a twilio function from another twilio function to retrieve the ID of a salesforce record. The following code is what gets returned from one function to another. I'm just trying to "read" the contents of the response to get the ID but can't seem to figure it out. I confirmed that the function returning the response works correctly (contains the right data.)
Help is much appreciated!
responsebody
2020-11-24T19:38:02.642Z 13c8fae2-5f74-40c2-942a-d6aa7ed85c48 INFO Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://coxczsdlk-dffcat-8307.twil.io/sf-get-record',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object] },
counter: 0 } }
Here's the code for the function returning this response - this line returns the correct ID - response.body.records[0].Id
const querystring = require('querystring');
const request = require('request');
let globalCallback;
exports.handler = function(context, event, callback) {
globalCallback = callback;
console.log("Starting");
console.log("event: ", event);
run(context.DOMAIN_NAME, event);
};
function run(domain, event){
request({
uri: `https://${domain}/sf-access-token`,
method: 'GET'
}, function (err, res, body) {
if(res.statusCode == 200){
// Received Access Token. Now build and send the request
processRequest(JSON.parse(body), event);
} else{
globalCallback(`Error getting token: ${res.body}`);
}
});
}
function processRequest(sfAuthReponse, event){
// if(validateRequest(event)) {
var options = {
// uri: `${sfAuthReponse.instance_url}/services/data/v43.0/query/?q=SELECT+id+From+${event.objectAPIName}+WHERE+callSID__c='${event.callSID}'`,
uri: `${sfAuthReponse.instance_url}/services/data/v43.0/query/?q=SELECT+id+From+Case+WHERE+callSID__c='1'`,
headers: {
'Authorization': 'Bearer ' + sfAuthReponse.access_token,
'Content-Type': 'application/json',
},
body: event.fields,
json:true,
method: 'GET'
};
request(options, processResponse);
// }
}
function validateRequest(event) {
let valid = false;
let validationMessage;
if(!event.objectAPIName || event.objectAPIName.trim().length === 0) {
validationMessage = "Parameter, objectAPIName, was not set in the JSON Request Body. Provide the SF API Name of the object to create";
} else if (!event.fields) {
validationMessage = "Parameter, fields, was not set in the JSON Request Body. Provide this parameter with a JSON value representing the fields to set when creating the SF object.";
} else {
valid = true;
}
if(!valid) {
globalCallback(validationMessage);
}
return valid; // <== This will always return true since execution is terminated with the callback if invalid
}
function processResponse(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('response.body.records[0].Id');
console.log(response.body.records[0].Id);
// Successfully created new object. Response 201 from successful object creation
//globalCallback(null, response.body.records[0].Id);
globalCallback(null, response);
} else{
console.log("Error: ", error);
console.log("Response: ", response);
console.log(body);
globalCallback(body);
}
}
and here's some of the code for the first function calling the above function, not sure how to dot notation into the response.
fetch('https://casdflk-dsfdsfat-8707.twil.io/sf-get-record', {
headers: {
'Authorization': 'Basic ' + context.ENCODED_TWILIO_CREDS,
'Content-Type': 'application/json'
},
method: 'POST',
body: {
objectAPIName: 'Case',
callSID: '1',
}
// callback(null,sid);
}).then(record => {
console.log('recordbody11');
console.log(record.body);
return record;
It looks like you are using fetch.
Fetch has a method .json() that you need to call on the response.
See the MDN page
Is that your question or did I miss something?

Vee-validate (VueJS) - evaluating a condition asynchronously

Can I make a custom validation rule that returns true/false based on a AJAX request? the problem is that the validate call has finished running when the AJAX call completes.
Do I need to have the rule set/unset a boolean variable based on which the field is valid/invalid?
const isValidNameRule = {
getMessage(field)
{
return "The name must be unique."
},
validate(validatingName)
{
var formData = new FormData();
formData.append("validatingName", validatingName);
this.$http.post("/api/isValid?name=" + validatingName, formData)
.then(function (response) {
// success
return true;
}, function (response) {
// error
return false;
});
}
};
Didn't know how to work with Promises.
Eventually got it working by extending one of the official samples:
const customRule = {
getMessage(field, params, data) {
return (data && data.message) || 'Something went wrong';
},
validate(aValue) {
return new Promise(resolve => {
var formData = new FormData();
formData.append("nameFilter", aValue);
$.ajax({
type: "POST",
url: url,
data: {
action: "validate",
value: aValue,
}
}).done(function (data) {
if (!ok)
{
resolve({
valid: false,
data: {message: "Condition not met"}
});
}
else
{
resolve({
valid: !! aValue,
data: undefined
});
}
});
});
}
};

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

Ajax request issue in sencha touch 2

I have a problem with sending an ajax request for the authentification..
i dont get errors but Network in chrome says : method : get , status : canceled , type : pending
and no response from this request ..
when i click on the file connection.js it point in this line :
// start the request!
xhr.send(requestOptions.data);
& my path name and the method get have the color RED
here is my code :
Ext.onReady(function() {
Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/',
method: 'GET',
useDefaultXhrHeader:false,
disableCaching: false,
timeout:120000,
params: {
client_id: 'xxxxxx',
client_secret: 'xxx',
format: 'json'
},
success: function(response) {
var resultat = Ext.JSON.decode(response.responseText);
//the response is : {"status":"ok","auth_token":"xxxxxxxxxxx"}
if (resultat.status === "ok") {
if (!resultat.access_token === "") {
access_token = resultat.access_token;
me.sessionToken = resultat.sessionToken;
}
else
{
new Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/signin',
method: 'post',
params: {
username: username,
password: password,
authtoken: resultat.access_token,
format: 'json'
},
success: function(response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
}
},
failure: function(response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
}
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
} else {
//exception
}
}
,
failure: function(response) {
me.sessionToken = null;
Ext.Msg.alert('failed !!'); // its what it shows me
}
});