Skip to content

Instantly share code, notes, and snippets.

@jgautheron
Created May 10, 2017 14:52
Show Gist options
  • Save jgautheron/044b88307d934d486f59ae87c5a5a5a0 to your computer and use it in GitHub Desktop.
Save jgautheron/044b88307d934d486f59ae87c5a5a5a0 to your computer and use it in GitHub Desktop.
Send client errors to the server
import ReactUpdates from 'react-dom/lib/ReactUpdates'
import ReactDefaultBatchingStrategy from 'react-dom/lib/ReactDefaultBatchingStrategy'
import 'isomorphic-fetch'
const logError = (err, extra = {}) => {
fetch('/logger', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: err.message,
callstack: err.stack,
stamp: new Date(),
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'server',
...extra,
}),
})
}
let isHandlingError = false
const ReactTryCatchBatchingStrategy = {
get isBatchingUpdates() { return ReactDefaultBatchingStrategy.isBatchingUpdates },
batchedUpdates(...args) {
try {
ReactDefaultBatchingStrategy.batchedUpdates(...args)
} catch (e) {
if (isHandlingError) {
throw e
}
isHandlingError = true
try {
logError(e)
} finally {
isHandlingError = false
}
}
},
}
ReactUpdates.injection.injectBatchingStrategy(ReactTryCatchBatchingStrategy)
server.post('/logger', (req, res) => {
console.log(req.body)
res.sendStatus(204)
})
@j-quelly
Copy link

Cool, but couldn't /logger be abused by some malicious user or bot? The logs could pretty quickly get polluted with a lot of noise.

@exbotanical
Copy link

exbotanical commented May 17, 2020

Cool, but couldn't /logger be abused by some malicious user or bot? The logs could pretty quickly get polluted with a lot of noise.

I wonder about this, too. I suppose we could add authentication to this route, but that just seems like a hack to me. Are there any plans to implement logging middleware in Next API routes (if this already exists, do let me know)?

@gamb
Copy link

gamb commented Mar 3, 2021

@MatthewZito Did you consider calling this inside an <ErrorBoundary /> at the root of the application instead? Curious if ReactUpdates.injection.injectBatchingStrategy has some properties that make it more suitable…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment