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