Skip to content

Instantly share code, notes, and snippets.

@nicgirault
Last active December 16, 2017 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicgirault/823438dc56c7c522a2aa027fa1f72fa1 to your computer and use it in GitHub Desktop.
Save nicgirault/823438dc56c7c522a2aa027fa1f72fa1 to your computer and use it in GitHub Desktop.
const ErrorStackParser = require('error-stack-parser')
const Slack = require('slack-node')
const config = require('../config')
const packageJson = require('../../package.json')
const slack = new Slack()
slack.setWebhook(config.slackHookUrl)
module.exports = (err, req, res, next) => {
// I don't want to send notifications for catched errors
// such as HTTP 400, 401, 404 errors. These errors
// created with npm http-errors have a `statusCode` attribute.
if (err.statusCode) return next(err)
// I don't want to raise errors on slack when I am
// working on my local environment
if (!config.slackHookUrl) return next(err)
// This is optionnal but convenient to get a
// github link to the code line that raised the error
const sourceLink = getSourceLink(err)
slack.webhook({
channel: config.errorChannel,
username: 'lalibot',
attachments: [
{
fallback: 'An uncaught error occured',
color: '#f67258',
title: 'An uncaught error occured on the Express API',
text: err.message + (sourceLink ? ` ${sourceLink}` : '')
}
]
}, (err) => {
// an error occurred when sending an error 🙄
logger.error(err.message)
})
return next(err)
}
const getSourceLink = (error) => {
if (!packageJson.repository || !packageJson.repository.url) return null
const branch = process.env.NODE_ENV === 'production' ? 'master' : 'staging'
const stack = ErrorStackParser.parse(error)
if (Array.isArray(stack)) {
// I can provide a link to source code only if it
// comes from our code. Not from node modules.
const stackItemsFromSrc = stack.filter((item) => item.fileName.match(/(src\/.*)$/))
if (stackItemsFromSrc.length > 0) {
const match = stackItemsFromSrc[0].fileName.match(/(src\/.*)$/)
if (match) {
return `<${packageJson.repository.url}/blob/${branch}/${match[1]}#L${stack[0].lineNumber}|See on Github>`
}
}
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment