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 all 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,6 +7,7 @@ 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')
Expand All @@ -15,6 +16,8 @@ const readingHistory = require('./routes/readingHistory')
const redirects = require('./routes/redirects')
const errorPages = require('./routes/errors')

checkErrors()

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

Expand Down
2 changes: 2 additions & 0 deletions server/routes/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,14 @@ module.exports = async (err, req, res, next) => {
const code = messages[err.message] || 500
log.error(`Serving an error page for ${req.url}`, err)
const inlined = await loadInlineAssets()

res.status(code)

res.format({
html: () => {
res.render(`errors/${code}`, {
inlineCSS: inlined.css,
isDev: process.env.NODE_ENV === 'development',
err,
template: inlined.stringTemplate
})
Expand Down
9 changes: 9 additions & 0 deletions server/routes/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

const search = require('../search')

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

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

const {getTree, getFilenames, getMeta, getTagged} = require('../list')
Expand Down Expand Up @@ -62,6 +65,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.format({
html: () => {
Expand Down
10 changes: 6 additions & 4 deletions server/userAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ 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'

const authStrategies = ['google', 'Slack']
let authStrategy = process.env.OAUTH_STRATEGY

Expand All @@ -38,8 +40,9 @@ if (isSlackOauth) {
} else {
// default to google auth
passport.use(new GoogleStrategy.Strategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
// some value must be passed to passport, but in dev this value does not matter
clientID: isDev ? ' ' : process.env.GOOGLE_CLIENT_ID,
clientSecret: isDev ? ' ' : process.env.GOOGLE_CLIENT_SECRET,
callbackURL,
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
passReqToCallback: true
Expand Down Expand Up @@ -82,7 +85,6 @@ router.get('/auth/redirect', passport.authenticate(authStrategy, {failureRedirec
})

router.use((req, res, next) => {
const isDev = process.env.NODE_ENV === 'development'
const passportUser = (req.session.passport || {}).user || {}
if (isDev || (req.isAuthenticated() && isAuthorized(passportUser))) {
setUserInfo(req)
Expand Down Expand Up @@ -111,7 +113,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