项目作者: toshi1127

项目描述 :
Error catcher middleware for mobx state tree.
高级语言: TypeScript
项目地址: git://github.com/toshi1127/mobx-state-tree-action-catch.git
创建时间: 2019-12-22T14:57:56Z
项目社区:https://github.com/toshi1127/mobx-state-tree-action-catch

开源协议:MIT License

下载


mobx-state-tree-action-catch

Error catcher middleware for mobx state tree.

Created with reference to redux-catch

Installing

  1. $ npm i mobx-state-tree-action-catch
  2. # or
  3. $ yarn add mobx-state-tree-action-catch

How to use

  1. import actionCatch from 'mobx-state-tree-action-catch';
  2. function errorHandler(error, snapshot: ReturnType<typeof getSnapshot>, lastAction: string) {
  3. console.error(error);
  4. console.error(snapshot)
  5. console.error(lastAction)
  6. }
  7. const Store = types.model({
  8. UIStore: types.optional(UIStore, {}),
  9. })
  10. export interface IStore extends Instance<typeof Store> {}
  11. const createStore = (snapshot = null): IStore => {
  12. MobxStore = Store.create()
  13. if (snapshot) {
  14. applySnapshot(MobxStore, snapshot)
  15. }
  16. // Add actionCatch to middleware
  17. addMiddleware(MobxStore, actionCatch(errorHandler))
  18. return MobxStore
  19. }
  20. export default createStore
  • actionCatch receive a function to use when an error happen.
  • The error handler function could be just a console.error like the example above or a function to log the error in some kind of error tracking platform.
  • You should use this middleware as the first middleware in the chain, so its allowed to catch all the possible errors in the application.

Using it with Sentry

To use it with Sentry just download the Sentry script from npm:

  1. npm i -S raven-js raven
  • raven-js: This is the client for browser usage.
  • raven-node: This is the client for server usage.

Now load and configure your client:

  1. import Raven from 'raven-js';
  2. const sentryKey = '<key>';
  3. Raven
  4. .config(`https://${sentryKey}@app.getsentry.com/<project>`)
  5. .install();

And then use Raven.captureException as the error handler like this:

  1. const createStore = (snapshot = null): IStore => {
  2. MobxStore = Store.create()
  3. if (snapshot) {
  4. applySnapshot(MobxStore, snapshot)
  5. }
  6. // Add actionCatch to middleware
  7. addMiddleware(MobxStore, actionCatch((error) => Raven.captureException(error), MobxStore))
  8. return MobxStore
  9. }