How to replace error message with an error page - javascript

I currently have when something goes wrong i display error text but i would like to replace this with a presentable error page instead of just text and wanted a little more help on how to go about this.
This is currently my code for displaying error text:
return function (req, res, next) {
errorRepo.get(req.get('error'), serviceTokenHandler.makeToken(), function (err, errorInfo) {
if (err || !errorInfo) {
res.status(500).render('error', {
message: 'This is my error message'
});
} else {
.....
next();
}
});
};
What do i need to do to redirect to an error page instead of just showing a message? Should i replace the inside of the if block with a method call that would redirect to another page?

I assume you are using express for your application. If you want to render a beautiful error page, you would do that just as you would render any other page.
The only difference between an error page and a "normal" page is - simply put - the http status code which ranges above 400.
E.g. you'd do:
...
if (err || !errorInfo) {
res.render('error-page', function(err, html) {
res.status(500).send(html);
});
}
...

Assuming you are using Express 4.x.
You can create an error.html file which you want to render when error occurs.
<html><body>
ERROR
</body> </html>
In node render the error.html when error occurs:
if(error) {
res.sendFile('error.html', { root: path.join(__dirname, '../views');
}
This way you can keep the html and node code seperate.
Express 4.x documentation for referance http://expressjs.com/en/4x/api.html#res.sendFile

Related

Node express return message with link

I've node program which in case of error needs to send error message ,
this works, however I want to add to the message also a link.
something like
Something went wrong and we cannot open your application.
Follow this tutorial to proceed.
And the this tutorial will be a link e.g. https://nodejs.org/en/about/
How can I do that?
...
} catch (e) {
throw new Error('Something went wrong and we cannot open your application.Follow this tutorial to proceed.'
)
}
And I send the data via express like res.send
app.get('/', async function (req, res) {
try {
const url = await invokeApp()
} catch (e) {
res.send(e.message)
}
})
update
while trying the suggestion below I able to get the link but the messege order was changed, any idea how to fix it ?
} catch (e) {
throw new Error('Something went wrong and we cannot open your application.Follow this tutorial to proceed.'
)
}
try this:
...
} catch (e) {
throw new Error('Something went wrong and we cannot open your application. Follow this tutorial to proceed.')
}
You can use res.send with html string -- i.e res.send('<p> html </p>') - and deal with on the other side.
Try this
res.json({ err : e.message , link : "error/url"})
and if error comes you could acces url from this object and display the link in front end.

Nodejs page not redirecting after POST

My problem is similar enough to this but also different and the answers aren't working for me.
I have a form to post and I need to display a message on the page whether it entered the data to the database successfully or not. So I have:
app.post('/add_new', upload.single('image'), function add_new(req, res, err)
{
var image = req.body.image;
// do some checks and try to insert
if (err){
res.render('page_name',{images:images, message:'There was an error'})
}
else{
images.push(image);
res.render('page_name',{images:images, message: 'Success'})}
}
}
The error/success messages are handled on the client side.
My problem is that it doesn't actually complete the post. It renders the page with the error/success message correctly but the URL looks like 'my_site.com/add_new', and if the user refreshes the page for any reason, it sends that 'form resubmission' alert, which causes problems. I need it to go back to 'my_site.com' and display the message.
I have found that doing
res.redirect('back')
returns to the correct page but obviously doesn't display the message.
I have noticed a few answers recommending
res.end('Success')
but that just displays a white page with the word 'Success' - I don't know how anyone thinks that's an acceptable solution!
EDIT:
Following Vinay's answer, my code now reads like:
app.post('/add_new', upload.single('image'), function add_new(req, res, err)
{
var image = req.body.image;
// do some checks and try to insert
if (err){
req.session.msg='error adding';
res.redirect('page_name');
}
else{
images.push(image);
req.session.msg='success';
res.redirect('page_name');
}
}
and this to get the page:
app.get('/page_name', is_logged_in, function(req, res) {
if(req.session.msg){
res.render('page_name', {images: images, user:req.user, message: req.session.msg});
setTimeout(req.session.msg="", 4000);
}
else{
res.render('page_name', {images: images, user:req.user, message:''});
}
});
But I am still finding that the error message persists when the page is refreshed. Have I made a mistake?
currently you are doing this
if (err){
res.render('page_name',{images:images, message:'There was an error'})
}
else{
images.push(image);
res.render('page_name',{images:images, message: 'Success'})}
}
you are getting url like this to 'my_site.com/add_new', which is correct rendering means your are loading/rendering html page to particular route which is '/add_new'.
There may be a two solution
1st solution
res.redirect('/?msg=' + string);
and on home page
app.get('/', function(req, res){
if(req.query.msg){
// display error message
}else{
// else do not display error
}
});
2nd solution
req.session.msg = "message here";
res.redirect('/');
and on home page you can do like this.
if(req.session.msg){
//display error message here
// after displaying msg in that last this
setTimeout(req.session.msg="", 3000); // this will clear a session after 3 seconds, so next time it will not display the msg.
} else {
//or display home page without error.
};
you can use one of them.

How to construct a non-custom error by Hand in Sails.js

I am writing a Service to be used by my Controllers in my Sails.js application.
If an error is thrown in the Service, I would like to return a error. I am used to the syntax of function callback(err, bar){ if (err) return error}. I am in a slightly different case, though. In the following code
function callBack(err, uploadedFiles){
if (err) return err;
if (uploadedFiles.length == {
return foo; //This is what needs to be of type "err"
}
});
}
}
So do I create a JSON object like
return { error: "error", message: 404}
I am not sure how to do this.
Why are you not using sails functions for responses? I am also new so excuse me if said something silly.
If you want to send a 404 status code which is for Not Found errors the you can use sails provided response res.notFound() like this:
return res.notFound({
message: "Some Message Here"
});
If you want to show completely custom message without any status code like 404 then use send() instead like this:
return res.send({
status: "404 or anything you like",
message: "Some Message Here"
});
Sorry, res.send() will also generate a status code but it will be 200 which means OK, so its a success code.
I believe it is:
{success:false, error: err}
You can raise your 404 error in your Services like this (assuming your service needs to work asynchronously):
var err = new Error('your message');
err.status = 404; // could be other HTTP status
return cb(err);
And in your calling function, you can handle the error like this:
SomeServices.somefunction(options, function (err, data) {
// res.negotiate(err) will automatically trigger res.notFound if err.status is 404
if (err) return res.negotiate(err);
/* your logic if not 404 */
}
The codes are quite simple here. Is that what you want?

How to create a ajax POST with node JS?

I am not sure how to use an ajax POST to POST from a Jade Page to Node JS. If someone can provide an example or tell me what I am missing from the script I have, please let me know.
This is the script file:
//Add friends
$('.addContact').click(function() {
$.post('/addContact',
{friendRequest: $(this).data('user')});
if($(this).html!=='Contact Requested') {
return $(this).html('Contact Requested');
}
});
The url I have for a POST on my app.js file is:
app.post('/addContact', user.addContactPost);
I am trying to post true for a click event on the button Add Contact and change it to Contact Requested if the data in the db is shown as true.
This is the jade file:
extends layout
block content
div
legend Search Results
div#userResults
for user in ufirstName
a(href='/user/#{user.id}')
p #{user.firstName} #{user.lastName}
button.addContact Add Contact
The route file is this:
exports.addContactPost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid, {
$push: {friendRequest: req.body.friendRequest}
}, function(err) {
if(err) {
console.log("post2");
return console.log('error');
//return res.render('addContactError', {title: 'Weblio'});
}
else {
console.log('postsuccess');
//alert('Contact added');
res.json({response: true});
}
});
};
If you are posting AJAX request, then you are expecting from JS on client-side to get some response, and react to this response accordingly.
If it would be separate request to another page - then probably rendering whole page - would be actual option.
But as you just need to get response from server and then update your front-end without reloading based on response, then you need to response from server on this POST request with some JSON. And then on client-side, do some templating, use jQuery or some templating libraries on client side for it.
Everything looks good I just think the $.post code is a little off. This might fix your problem.
$('.addContact').click(function() {
$.post('/addContact', { addContact : true }, function(data){
console.log('posting...');
$('.addContact').html(data);
});
...
});
The object I added to the $.post is what is going to be sent to the server. The function you specified at the end is your callback. It's going to be called when the function returns. I think that may have been some of your confusion.
Your node route should look something like this
exports.addContactPost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid,{
addContact: req.body.addContact
}, function(err) {
if(err) {
console.log("post2");
res.render('addContactError', {title: 'Weblio'});
}
//assuming express return a json object to update your button
res.json({ response : true });
});
};

Passing error message to template through redirect in Express/Node.js

In my Node.js application, I have a function (routed by Express) which presents a form to the user:
app.get('/register', function (req, res) {
res.render('form');
});
I have another function, routed to the same URL, but which handles POST requests, which receives the data submitted by the previous form. If the form does not validate, it redirects the user back to the form; otherwise, it does what should be done:
app.post('/register', function (req, res) {
if (validate(req.registerForm)) return res.redirect('back');
persistStuff(req.registerForm, function (err, data) {
// Do error verification etc.
res.redirect('back')
});
});
What I want to do is to send a error message to be presented, in the line:
if (validate(req.registerForm)) return res.redirect('back');
To write something like
if (validate(req.registerForm)) return res.render('form', {msg:'invalid'});
is unacceptable because I want to follow the POST-REDIRECT-GET pattern. I could do something like
if (validate(req.registerForm)) return res.redirect('/register?msg=invalid');
but it would hardcode an URL in my code and I'd prefer to avoid it. Is there another way to do it?
You need to use flash notifications, and it is built into express.
You'll add a message like so: req.flash("error", "Invalid form...");
You'll need a dynamic handler to add the messages to your rendered template, or you can check out the ones TJ has made for express. (express-messages)
You could simply have it redirect as res.redirect('..?error=1')
the ? tag tells the browser that it is a set of optional parameters and the .. is just a pathname relative recall (like calling cd .. on terminal to move back one directory)
and you're browser will direct to the appropriate page with that tag at the end: http://.....?error=1
then you can simply pull the error on the appropriate page by doing a:
if (req.param("error" == 1)) {
// do stuff bassed off that error match
};
you can hardcode in several different error values and have it respond appropriately depending on what error occurred

Categories

Resources