improve error handling

This commit is contained in:
Ondrej Synacek 2019-10-17 22:36:29 +02:00
parent a94d3a3550
commit 4297d5aa64
3 changed files with 44 additions and 16 deletions

View File

@ -5,6 +5,7 @@ const path = require('path')
const crawl = require('./crawler') const crawl = require('./crawler')
const parseHTML = require('./parser') const parseHTML = require('./parser')
const generateICS = require('./ics') const generateICS = require('./ics')
const { genericErrorHandler, checkFBURL } = require('./middlewares')
const port = process.env.PORT const port = process.env.PORT
const app = express() const app = express()
@ -21,18 +22,16 @@ app.get('*', (req, res) => {
res.status(400).render('404') res.status(400).render('404')
}) })
app.get('/error', (req, res) => {
res
.status(500)
.render('error', { error: req.error || '' })
})
app.use('/download', checkFBURL)
app.post('/download', async (req, res) => { app.post('/download', async (req, res) => {
const { url } = req.body const { url } = req.body
if (!/facebook/.test(url)) {
return res
.status(500)
.render(
'error',
{ error: 'Not Facebook URL!' }
)
}
try { try {
const html = await crawl(url) const html = await crawl(url)
const data = parseHTML(html) const data = parseHTML(html)
@ -44,15 +43,12 @@ app.post('/download', async (req, res) => {
.send(200, new Buffer(ics, 'utf8')) .send(200, new Buffer(ics, 'utf8'))
} }
} catch (err) { } catch (err) {
console.error(err) return next(err)
return res
.status(500)
.render('error', { error: err.toString() })
} }
return res.render('download', { url })
}) })
app.use(genericErrorHandler)
app.listen(port, () => { app.listen(port, () => {
console.log(`App running on port ${port}`) console.log(`App running on port ${port}`)
}) })

33
lib/middlewares.js Normal file
View File

@ -0,0 +1,33 @@
const FBURLError = () => new Error('Not a valid Facebook URL!')
const genericErrorHandler = (err, req, res, next) => {
console.error(err.stack)
res
.status(500)
.render('error', { error: err.toString() })
}
const checkFBURL = (req, res, next) => {
const { url } = req.body
if (!url) {
return next(FBURLError())
}
try {
const FBURL = new URL(url)
if (!(/facebook/.test(FBURL.hostname))) {
return next(FBURLError())
}
} catch (err) {
return next(err)
}
return next()
}
module.exports = {
genericErrorHandler,
checkFBURL,
}

View File

@ -84,7 +84,6 @@ const parseHTML = (html) => {
{} {}
const data = parseEventData(eventData) const data = parseEventData(eventData)
console.log(data)
return data return data
} catch (err) { } catch (err) {
throw err throw err