Is it possible to know that the error is CORS in Axios? - axios

Axios gives us the interception ability. I have created a response interceptor to get errors.
This is my code:
const errorInterceptor = error => {
if (error.code === 'ERR_NETWORK') {
throw new Error('Network is not connected')
}
// The rest of the code
}
However, if I get the CORS error, I can't find any information to know that it was a CORS error.
Why do I need this?
I want to provide meaningful messages to my users.
If network is disconnected, I want to show You are not connected to the internet. If it's CORS, I want to show API is not configured properly for CORS, please inform the administrator.
How can I know whether the error is CORS or not?
I have created an interceptor and I have tried to extract data from it.

axios.interceptors.response.use((response) => response, (error) => {
if (typeof error.response === 'undefined') {
alert('A network error occurred. '
+ 'This could be a CORS issue or a dropped internet connection. '
+ 'It is not possible for us to know.')
}
return Promise.reject(error)
})

Related

How can I know the type of error and response code from IOWebSocketChannel

I am trying to know if the connection error is Connection to 'some URL' was not upgraded to websocket. Also identify response code. The server is emitting 401.
I need this to know if I need to refresh the token and then reconnect.
final channel = IOWebSocketChannel.connect(Url)
final sub = channel.stream.listen((data){
//process data
},
onError: (error){
//confirm this error failing to upgrade and
// response code is 401
// then refresh token and reconnect
})
To know the error type
print('error type is ${error.runtimeType}');
then you can handle it
if(error is errorType)
{
...
}

Angular 2 how to read Custom error message from backend

My problem with Angular 2 that was not exist in AngularJS, that I was sending the error message as a string with backend API call in case I have error, with error status 401 as example, the problem now that I can't read this message from Angular2 http response message, while I can do that from AngularJS:
I tried the following codes and nothing was helpful:
Promise:
this._http.post('/login',{email: 'email#example.com', password: '123'})
.toPromise()
.then((resp) => console.log(resp), (error) => console.log(error));
Observable:
this._http.post('/login',{email: 'email#example.com', password: '123'})
.subscribe(response =>console.log(response), (error) => console.log(error));
And from back-end I send response as a text, for OK or Unauthorized, for OK i send back String token == UUID.randomUUID().toString();, for error I send back message like String error = " Invalid credentials ";, the problem is that the console.log works and print the text for success (token in this case), but in case error, its just prints: Response with status: 200 for URL: null.
If I change code to JSON.stringify(error) I get something like this:
{"_body":{},"status":401,"ok":false,"statusText":"Unauthorized","headers":{"null":["HTTP/1.1 401 Unauthorized"],"Access-Control-Allow-Headers":["Origin"," X-Requested-With"," Content-Type"," Accept"," Referer"," User-Agent"],"Access-Control-Allow-Met
hods":["POST"," GET"," PUT"," DELETE"," OPTIONS"],"Access-Control-Allow-Origin":["*"],"Allow":["*"],"Content-Length":["36"],"Content-Type":["text/plain; charset=utf-8"],"Date":["Tue"," 23 Aug 2016 14:53:25 GMT"]},"type":2,"url":null}
As you can see the error test not even mentioned inside the Object !!
I tried to change the response for error from backend to return json like this:
{
"message": "invalid email or password"
}
I can get the result inside _body, and I can only read it like this: console.log(error._body.message) ! but i feel its something wrong this way, and I don't want to response as a json in this case.
For angularjs (angular 1), its so simple just to print the response and everything is cool, while in angular 2 its a really problem.
What the problem, and how I can solve this issue without any refactor to backend?
Edit:
I'm using Angular 2.0.0-rc.4 and same for http : `"#angular/http": "2.0.0-rc.4"
Mothanfar
In my case I'm working with the Asp Web Api as back end,this thing is making me crazy as well, the only solution I found is transform in a json and read the message, I know is really ugly but works for me.
Regards.
CheckError(error: any) {
let servermsg: any = JSON.parse(error._body)["ModelState"]["Login"][0];
if (servermsg) {
this.showMsg = true;
this.msg = servermsg;
}
}
If you are returning JSON object from the server, you may use the below code at client side:
let errMsg: ErrorMessage = err.json();
console.log(errMsg.message)
export class ErrorMessage {
message:string;
}

Openfire in-band-registration via Bosh not working with Strophe/Strophe.register.js

I previously asked a similar question about ejabberd, however ejabberd was giving other problems, so I switched to openfire. For the sake of not making the original qestion to cluttered, I decided to create a new question, since this question pertains to openfire and is a different issue than the one I was having with ejabberd.
So, here goes the question:
I have a strophe.js xmpp client, which connects to an openfire 3.10.0 alpha server running on the Amazon cloud. I need 3.10.0 alpha over 3.9.3 because of a bfix which is included in the former, but not the latter.Anyway, since this is a strophe client, I have enabled bosh, and I can see it running at myAWSDNS.com:7070. I am able to connect to the server via my client using this bosh service and existing accounts, and send messages back and forth so it seems to be functioning ok.
I would also like to add in-band registration, for which I use strophe.register.js
This is the code I use for this:
var tempConn = new Strophe.Connection("http//myAWSDNS.com:7070/http-bind/");
tempConn.register.connect("myAWSDNS.com", function (status) {
if (status === Strophe.Status.REGISTER) {
// fill out the fields
connection.register.fields.username = "juliet";
connection.register.fields.password = "R0m30";
// calling submit will continue the registration process
connection.register.submit();
} else if (status === Strophe.Status.REGISTERED) {
console.log("registered!");
// calling login will authenticate the registered JID.
connection.authenticate();
} else if (status === Strophe.Status.CONFLICT) {
console.log("Contact already existed!");
} else if (status === Strophe.Status.NOTACCEPTABLE) {
console.log("Registration form not properly filled out.")
} else if (status === Strophe.Status.REGIFAIL) {
console.log("The Server does not support In-Band Registration")
} else if (status === Strophe.Status.CONNECTED) {
// do something after successful authentication
} else {
// Do other stuff
}
});
This seems to work fine, as it enters the first if-bracket (status === Strophe.Status.REGISTER), and tries to set connection.register.fields.username = "juliet";
However, here, when executing that line, it jumps into strophe.js line 2476:
if (this.connect_callback) {
try {
this.connect_callback(status, condition);
} catch (err) {
Strophe.error("User connection callback caused an " +
"exception: " + err);
}
}
where 2476 is the code in the catch(err) { ...... } bracket.
If I inspect err, this is what I get:
So message: connection is not defined and, obviously, the regstration doesnt work, and I am not sure why. Does anyone have any input on this?
Thanks, and best regards,
Chris
You might not like this answer... The reason for connection == undefined is because you named it tempConn.

Error Handling in Sails.js

I am just starting using Sails.js and it's an amazing framework. But I've met some situation and I cannot find solution by Google so I came here for help.
I have a controller to connect to another remote service with very old-designed API full of XML response and inconsistency, wrapping that service in simple and clean APIs. So I have some routers like:
list: function(req, res) {
params = {
...
}
FooService.request(data, function(error, response) {
res.send(response)
})
process.once('uncaughtException', function(err) {
res.send(500, '[Foo] ' + err);
});
},
The 'process.once' is for async exceptions which may raised in the FooService.request process. I know this is bad code and my question is: how to handle such situation more Sails.js way?
In Node.js we have Domain and connect-domain, which are designed for such problems. Because Sails.js is basically Express, which can facilitate connect-domain very well, I think there may be some idiomatic way to do that.
I've tried adding this in config/local.js:
module.exports = {
...
express: {
customMiddleware: function(app) {
console.log('Custom middleware config called')
var domain = require('connect-domain')
app.use(domain())
.use(function(err, req, res, next) {
console.log('Error catched!')
res.send(500, '[Foo] ' + err)
})
}
}
};
When un-catched exception occurred, it will not crash server and error 500 being returned to client side ('app.use(domain())' works). But the custom error handler does not called. Have no idea why.
If you're in control of the FooService code, then the best option is to handle all errors that happen there by calling the callback for FooService.request early with the error, and then using res.serverError or some other response in your controller:
FooService.request(data, function(error, response) {
if (error) {return res.serverError(errror);}
res.send(response)
});
If the FooService is using packages that you don't control, which may themselves throw errors inside of async code that they aren't catching (bad code!) then another good option is to use Node's error domains. See this answer for an example of someone doing a quick wrapper to use domains to catch errors in asynchronous code.

Error handling with Mongoose

I am an absolute NodeJS beginner and want to create a simple REST-Webservice with Express and Mongoose.
Whats the best practice to handle errors of Mongoose in one central place?
When anywhere an database error occurs I want to return a Http-500-Error-Page with an error message:
if(error) {
res.writeHead(500, {'Content-Type': 'application/json'});
res.write('{error: "' + error + '"}');
res.end();
}
In the old tutorial http://blog-next-stage.learnboost.com/mongoose/ I read about an global error listener:
Mongoose.addListener('error',function(errObj,scope_of_error));
But this doesn't seem to work and I cannot find something in the official Mongoose documentation about this listener. Have I check for errors after every Mongo request?
If you're using Express, errors are typically handled either directly in your route or within an api built on top of mongoose, forwarding the error along to next.
app.get('/tickets', function (req, res, next) {
PlaneTickets.find({}, function (err, tickets) {
if (err) return next(err);
// or if no tickets are found maybe
if (0 === tickets.length) return next(new NotFoundError));
...
})
})
The NotFoundError could be sniffed in your error handler middleware to provide customized messaging.
Some abstraction is possible but you'll still require access to the next method in order to pass the error down the route chain.
PlaneTickets.search(term, next, function (tickets) {
// i don't like this b/c it hides whats going on and changes the (err, result) callback convention of node
})
As for centrally handling mongoose errors, theres not really one place to handle em all. Errors can be handled at several different levels:
connection errors are emitted on the connection your models are using, so
mongoose.connect(..);
mongoose.connection.on('error', handler);
// or if using separate connections
var conn = mongoose.createConnection(..);
conn.on('error', handler);
For typical queries/updates/removes the error is passed to your callback.
PlaneTickets.find({..}, function (err, tickets) {
if (err) ...
If you don't pass a callback the error is emitted on the Model if you are listening for it:
PlaneTickets.on('error', handler); // note the loss of access to the `next` method from the request!
ticket.save(); // no callback passed
If you do not pass a callback and are not listening to errors at the model level they will be emitted on the models connection.
The key take-away here is that you want access to next somehow to pass the error along.
hey this is the simplest way i found..
try { } catch (error) {
console.log(error);
// checking validation
if (error.name === "ValidationError") {
const message = Object.values(error.errors).map(value => value.message);
return res.status(400).json({
error: message
})
}
res.status(400).json(error.message)
}
}
just copy paste