From ad361adab1e9605656cd12876386498b2cb6781e Mon Sep 17 00:00:00 2001 From: sudoer777 <78781902+sudoer777@users.noreply.github.com> Date: Fri, 26 Nov 2021 16:46:46 -0700 Subject: [PATCH] Improve error handling for divisions --- routes/manage.js | 45 +++++++++++++++++++----------------- views/manage/adddivision.pug | 1 + 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/routes/manage.js b/routes/manage.js index 4558cfd..9b5fe6e 100644 --- a/routes/manage.js +++ b/routes/manage.js @@ -114,31 +114,34 @@ router.post('/sport', checkLoginStatus.admin, async function(req, res, next) { router.get('/division', checkLoginStatus.admin, function(req, res, next) { let title = req.query.division ? 'Edit Division' : 'Add Division' - res.render('manage/adddivision', { title, userLoggedIn: !!req.user }); + res.render('manage/adddivision', { title, userLoggedIn: !!req.user, message: req.flash('error') }); }); -router.post('/division', checkLoginStatus.admin, function(req, res, next) { - const name = req.body['name']; - const sport = req.body['sport']; - const genderName = req.body['gender']; - - const id = req.body['division']; - const remove = req.body['remove']; - - - if(remove) divisions.remove(id).then(res.redirect('/manage')); - else if(id) divisions.rename(id, name).then(res.redirect('/manage')); - else { - if(genderName == "both") { - divisions.add(name, genders.FEMALE, sport) - .then(divisions.add(name, genders.MALE, sport) - .then(res.redirect("/manage"))); - } +router.post('/division', checkLoginStatus.admin, async function(req, res, next) { + try { + const name = req.body['name']; + const sport = req.body['sport']; + const genderName = req.body['gender']; + + const id = req.body['division']; + const remove = req.body['remove']; + + if(remove) await divisions.remove(id); + else if(id) await divisions.rename(id, name); else { - const gender = (genderName == "female") ? genders.FEMALE : genders.MALE; - divisions.add(name, gender, sport) - .then(res.redirect("/manage")); + if(genderName == 'both') { + await divisions.add(name, genders.FEMALE, sport); + await divisions.add(name, genders.MALE, sport); + } else { + const gender = (genderName == "female") ? genders.FEMALE : genders.MALE; + await divisions.add(name, gender, sport); + } } + res.redirect('/manage'); + } catch(err) { + console.error("ERROR: " + err.message); + req.flash("error", "An error has occurred."); + res.redirect('/manage/division'); } }); diff --git a/views/manage/adddivision.pug b/views/manage/adddivision.pug index 10e7281..1a17aaf 100644 --- a/views/manage/adddivision.pug +++ b/views/manage/adddivision.pug @@ -21,6 +21,7 @@ block content label Division name span(class='form-section-input') input#name-textbox(type="text", name="name" disabled) + .error #{message} span(class='form-section') button#submit-button(type="submit" disabled) Submit span(class='form-section')