JQuery post request with Express error handling - javascript

I am making the following request in the front-end with jquery:
try {
await $.post("/test", data, () => {
console.log("received");
})
}
catch (error) {
console.log(error.status);
}
The request is received by a back-end Express router:
app.post("/test", (req, res) => {
console.log("test received")
res.status(400).send("Error message");
})
The back-end sends an error message of the status 400. Although the error is getting caught by the catch statement in the front-end, and the error is being displayed, the browser console still displays the red error of Failed to load resource: the server responded with a status of 400 (Bad Request).
I am wondering if as a best practice, it is ok to have that error message to show up on the browser? I thought about it, and don't see any issue that the error would cause. Furthermore, what would be some of the best practices to handle error return by front-end jQuery/HTTP requests.

Related

node-fetch HTTP Errors not being caught

I am having some problems with catching nodejs fetch exceptions
What I am expecting to happen is:
HTTP error of some sort occurs in my fetch call
CheckResponseStatus function runs and an error an error is thrown with the server error status and text
This error is caught and the ServerError function runs which (just for testing) will just print the error to the console.
However, the error printed to the console is:
Cannot connect to Server. Check you are using the correct IP Address and the server is running.
FetchError: request to http://localhost:3689/api/outputs failed, reason: connect ECONNREFUSED 127.0.0.1:3689
This is implying that the error I have thrown is not being caught, some default fetch error is being caught, and CheckResponseStatus is not being run.
My code is below
Node-Fetch HTTP Request:
async function getStatus(serverip,serverport){
return await fetch(`http://${serverip}:${serverport}/api/outputs`)
.then(this.checkResponseStatus)
.then(res => res.json())
.catch((err) => this.ServerError(err));
}
CheckResponseStatus Function:
checkResponseStatus(res) {
if(res.ok){
return res
}
//will add elseif's here for different HTTP errors
else {
throw new Error(`The HTTP status of the response: ${res.status} (${res.statusText})`);
}
}
ServerError Function:
ServerError(err){
console.log('Cannot connect to Server. Check you are using the correct IP Address and the server is running.');
console.log(err);
}
Thanks for any suggestions or help.
If fetch is unable to connect to the remote server, it will reject. In your code, checkResponseStatus is never called because fetch is never able to get a response; the first two .then blocks are skipped because fetch rejected, so execution goes directly to the .catch block.
If you want network errors to run through checkResponseStatus, you can add a second .catch before the first .then and format the error into a "response":
fetch(`http://${serverip}:${serverport}/api/outputs`)
.catch(err => {
// return a mock failed response for checkResponseStatus to handle
return {
ok: false,
status: -1,
statusText: 'Network Failure',
};
})
.then(this.checkResponseStatus)
.then(res => res.json())
.catch((err) => this.ServerError(err));
However, I believe your code is currently running how I would expect it to - a network failure skips checkResponseStatus, which makes sense because there's no real response to check.

Error: "Request failed with status code 500" con laravel en axios.put()

I am learning to work with laravel in this case version 5.6, by implementing a code with axios to update a table on my web page, I get the following message enter image description here the code I'm having problems with is the next
actualizarCategoria(){
if (this.validarCategoria()){
return;
}
let me = this;
axios.put('/categoria/actualizar',{
'nombre': this.nombre,
'descripcion': this.descripcion,
'id': this.categoria_id
}).then(function (response) {
me.cerrarModal();
me.listarCategoria();
}).catch(function (error) {
console.log(error);
});
}
I would say that error 500 = error form your server. So your request may be malformed or it is a bug in your API (laravel side). Check your PHP logs you should see an error and look at the network tab in chrome to see the response from the server

Get Axios frontend Promise to receive errors msg from Rails backend

In Rails I'm returning:
render json: { errors: e.response.body.errors }, status: 400
In JavaScript I'm using Axios:
axios.patch('/settings/account', {}, {params: {...
} })
.then((e)=> {
...
console.log('submitted')
})
.catch(function (error, res) {
// only get error that gives 400, but not error msg here, res isn't here
console.log(error);
});
How do I get the e.response.body.errors on my frontend?
Axios reject promises if the server response http status code is anything but 2xx. I see you are sending an error response from the server, but are you sending this response through a http error status? If you arent, the error isnt an error to axios, so the error would show in the "then()" hook, since the promise is resolved.
If you are, then you should see the error whithin error.response.data

How do I get the full error message from my Node and Express server on the client side?

I have an express route that returns a 400 status and an error message. I want to alert the full error message on the client-side, but the alert only says "Object object" when I alert it. I inspected that object and I don't see the full error message that I see logged to my terminal from the server.
On the server the error message says, "djhbf is not defined" because I typed in some random characters to throw an error message. On the client-side, the object has some properties, but none of them contain the error message "djhbf is not defined". The closest thing to an error message is, "status-text: bad request". How do I retrieve the actual error message "djhbf is not defined" on the client-side?
Here is my server.js code which sends the error message in its catch block of a promise:
app.post('/sendEmails', function(req, res, next) {
axios.get(FEED_URL)
.then(data => {
let jobs = data.data.jobs;
fetchClients(jobs, 'email').then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.log(err);
res.status(400).json(err);
})
})
.catch(error => {
console.log(error);
});
});
Here is the client-side code which alerts the error:
sendEmails() {
axios.post("/sendEmails")
.then(res => {
this.setState({
emailsSent: true,
smsSent: false
});
})
.catch((err) => {
console.log(err);
alert(err);
});
}
Updated
This is not an express issue. axios decorates the error object. You just need to change your client side console.log to this: console.log(err.response.data);
You will also need to update your server side logic since you are using axios on both sides. Try res.status(400).json({msg: 'There was a problem with your request'});
If that works you'll just need to drill down in the err object on the server side to see what you want to send back to the client.
See the Error Handling section of the axios docs.

Error handling in express while piping stream to response

I'm having some problem with handling errors in a Express js app.
My problem is that I'm piping a stream to response, and I don't know what is the best method
to handle error that could occur in the readable stream.
I'm using errorHandler middleware, configured just after route middleware:
...
app.use(app.router);
app.use(express.errorHandler());
...
And this is my route:
exports.folders = function(req, res, next) {
//throw new Error("TEST ERROR");
var path = decodeURIComponent(req.params.path),
foldersStream = wd.listFolders(path);
foldersStream.on("error",function(err){
console.log("STREAM ERROR")
console.dir(next.name)
return next(err);
});
res.setHeader("content-type", "application/json");
foldersStream.pipe(res);
};
If I throw the TEST ERROR in the body of the function, it is handled as expected by express errorHandler.
Anyway, if an error event is emitted in the stream, the error event handler get called, because I can see the message in console, but errorHandler never get called.
If I don't handle the error event, the whole node process crash. If I handle it, the server send a 500 response to client, but errorHandler is not called, so I miss the stack trace in the log.
What I'm doing wrong?
Your code is correct: the problem is that the resonse is partially returned when the error occured.
Once the folderStream starts to pipe data into the response, the errorHandler is unable to write your stacktrace when invoked by next(err).
In that case, the browser (or http client) received a cancelled response.

Categories

Resources