Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active September 17, 2025 12:30
Show Gist options
  • Select an option

  • Save luizbills/0f5550f4f6732df8bb1be51b3236c807 to your computer and use it in GitHub Desktop.

Select an option

Save luizbills/0f5550f4f6732df8bb1be51b3236c807 to your computer and use it in GitHub Desktop.
Function to catch and handle browser errors. Useful while developing a project.
/**
* Catch browser errors. Useful while developing.
*
* @author Luiz Bills <[email protected]>
* @licese MIT
* @version 1.2
*
* @param {(message: string, event: Event) => void} callback A function called when an error happens
* @returns {function} A function to remove the event listeners
*/
export const onError = /** @__PURE__ */ (callback) => {
const handleError = (event) => {
callback(event.reason ? event.reason.message : event.message, event)
return false
}
window.addEventListener("error", handleError)
window.addEventListener("unhandledrejection", handleError)
return () => {
window.removeEventListener("error", handleError)
window.removeEventListener("unhandledrejection", handleError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment