Mobx: Best practise for handling ajax errors

Created on 9 Aug 2016  路  3Comments  路  Source: mobxjs/mobx

Firstly I want to say many thanks to mobx which is the great state management tool we have used in the production and we love it! Recently I was thinking of coding a general error handling module for our app. Things like working with axios and react-router, we need to implement an auto redirect upon token expiration to login page, and an error page for user to choose to abort or refetch data if there is network error(broken link, or sluggish network), I guess the best place for mobx is to create these things in the domain store, but I would like to get some example code for guidance. Would appreciate if any body has similar solution!

Most helpful comment

I usually do a similar thing, have a store for some globally important information like authentication and also an observable that holds the current error state. If any (unexpected one that is), that is nicely rendered by one of the top level components.

All 3 comments

@geohuz, I think, handling network errors is beyound MobX concern. There is nothing preventing you from changing some flag in your domain store or calling some method if you need this, for example:

class MyStore {
  @observable lastError;

  constructor() {
    axios.interceptors.response.use(
      response => response,
      error => {
        this.lastError = error;
        return Promise.reject(error);
      }
    );

    // OR:

    window.onerror = (message, source, lineno, colno, error) => {
       this.lastError = error;
    };
  }
}

I usually do a similar thing, have a store for some globally important information like authentication and also an observable that holds the current error state. If any (unexpected one that is), that is nicely rendered by one of the top level components.

Closing the question. Feel free to re-open if things are unclear

Was this page helpful?
0 / 5 - 0 ratings