Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved error handling #178

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions layouts/errors/500.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
<div class="tagline">
<h1><%- template('error.500.heading') %></h1>
<p><%- template('error.500.message') %></p>
<% if (locals.isDev && locals.err && locals.err.message) { %>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Should we include the full trace here, too?

<p><strong>Error:</strong> <%- locals.err.message %></p>
<% } %>
</div>
<%- include('../partials/search', {style: 'homepage'}) %>
</div>
Expand Down
22 changes: 22 additions & 0 deletions server/errors/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const messages = require('./messages')

// For now, this should just throw for things that would stop the app from booting.

module.exports = () => {
const { errorMessages } = messages
const { APPROVED_DOMAINS, DRIVE_TYPE, DRIVE_ID } = process.env
const errors = []

if (!APPROVED_DOMAINS) errors.push(errorMessages.noApprovedDomains)
if (!DRIVE_TYPE) errors.push(errorMessages.noDriveType)
if (!DRIVE_ID) errors.push(errorMessages.noDriveID)

if (errors.length) {
console.log('***********************************************')
console.log('Your library instance has configuration issues:')
errors.forEach((message) => console.error(` > ${message}`))
console.log('Address these issues and restart the app.')
console.log('***********************************************')
process.exit(1)
}
}
8 changes: 8 additions & 0 deletions server/errors/messages.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"errorMessages": {
"noApprovedDomains": "You must set the APPROVED_DOMAINS environment variable to a list of domains or a regular expression.",
"noDriveType": "No DRIVE_TYPE env variable set. Please set it to 'team' or 'folder.'",
"noDriveID": "No DRIVE_ID env variable set. Set this environment variable to the ID of your drive or folder and restart the app.",
"noFilesFound": "No files found. Ensure your DRIVE_ID and DRIVE_TYPE environment variables are set correctly and that your service account's email is shared with your drive or folder.\n\nIf you just added the account, wait a minute and try again."
}
}
3 changes: 3 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ const csp = require('helmet-csp')
const {middleware: cache} = require('./cache')
const {getMeta} = require('./list')
const {allMiddleware, requireWithFallback} = require('./utils')
const checkErrors = require('./errors')
const userInfo = require('./routes/userInfo')
const pages = require('./routes/pages')
const categories = require('./routes/categories')
const playlists = require('./routes/playlists')
const readingHistory = require('./routes/readingHistory')
const errorPages = require('./routes/errors')

checkErrors()

const userAuth = requireWithFallback('userAuth')
const customCsp = requireWithFallback('csp')

Expand Down
1 change: 1 addition & 0 deletions server/routes/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ module.exports = async (err, req, res, next) => {
const inlined = await loadInlineAssets()
res.status(code).render(`errors/${code}`, {
inlineCSS: inlined.css,
isDev: process.env.NODE_ENV === 'development',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

err,
template: inlined.stringTemplate
})
Expand Down
10 changes: 9 additions & 1 deletion server/routes/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

const search = require('../search')
const move = require('../move')
const { getAuth } = require('../auth')
const { errorMessages } = require('../errors/messages.json')

const router = require('express-promise-router')()

Expand All @@ -14,7 +16,7 @@ router.get('/:page', handlePage)
router.get('/filename-listing.json', async (req, res) => {
res.header('Cache-Control', 'public, must-revalidate') // override no-cache
const filenames = await getFilenames()
res.json({filenames: filenames})
res.json({ filenames: filenames })
})

module.exports = router
Expand Down Expand Up @@ -57,6 +59,12 @@ async function handlePage(req, res) {

if (page === 'categories' || page === 'index') {
const tree = await getTree()
if (!tree.children) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 This signal is great. It also seems like we could easily make this nonfatal (log, but have the library site be empty) if we wanted.

// pull the auth client email to make debugging easier:
const authClient = await getAuth()
const errMsg = errorMessages.noFilesFound.replace('email', `email (<code>${authClient.email}</code>)`)
throw new Error(errMsg)
}
const categories = buildDisplayCategories(tree)
res.render(template, { ...categories, template: stringTemplate })
return
Expand Down
13 changes: 9 additions & 4 deletions server/userAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@ const {stringTemplate: template} = require('./utils')
const router = require('express-promise-router')()
const domains = new Set(process.env.APPROVED_DOMAINS.split(/,\s?/g))

const isDev = process.env.NODE_ENV === 'development'

// some value must be passed to passport, but in dev this value does not matter
const clientId = isDev ? ' ' : process.env.GOOGLE_CLIENT_ID
const clientSecret = isDev ? ' ' : process.env.GOOGLE_CLIENT_SECRET

passport.use(new GoogleStrategy.Strategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
clientID: clientId,
clientSecret: clientSecret,
callbackURL: '/auth/redirect',
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
passReqToCallback: true
Expand Down Expand Up @@ -51,7 +57,6 @@ router.get('/auth/redirect', passport.authenticate('google'), (req, res) => {
})

router.use((req, res, next) => {
const isDev = process.env.NODE_ENV === 'development'
const passportUser = (req.session.passport || {}).user || {}

if (isDev || (req.isAuthenticated() && isAuthorized(passportUser))) {
Expand Down Expand Up @@ -81,7 +86,7 @@ function isAuthorized(user) {
}

function setUserInfo(req) {
if (process.env.NODE_ENV === 'development') {
if (isDev) { // userInfo shim for development
req.userInfo = {
email: process.env.TEST_EMAIL || template('footer.defaultEmail'),
userId: '10',
Expand Down
7 changes: 5 additions & 2 deletions server/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ exports.requireWithFallback = (attemptPath) => {
return require(customPath)
} catch (err) {
// if the file exists but we failed to pull it in, log that error at a warning level
const level = fs.existsSync(customPath) ? 'warn' : 'debug'
log[level](`Failed pulling in custom file ${attemptPath} @ ${customPath}. Error was:`, err)
// with no stacktrace.
const fileExists = fs.existsSync(customPath)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 This also seems like a useful signal. Let's make sure it merges cleanly with the other open PR for this case, https://github.com/nytimes/library/pull/202/files

const level = fileExists ? 'warn' : 'debug'
const toLog = fileExists ? err : 'No override file given.'
log[level](`Failed pulling in custom file ${attemptPath} @ ${customPath}. Error was:`, toLog)
return require(serverPath)
}
}
Expand Down