aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/GlobalErrorStore.js
blob: 9c851d6f269a501cbeec654c5ee92782f68fbc4a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { observable, action } from 'mobx';
import Store from './lib/Store';
import Request from './lib/Request';

export default class GlobalErrorStore extends Store {
  @observable error = null;

  @observable messages = [];

  @observable response = {};

  constructor(...args) {
    super(...args);

    window.addEventListener('error', (...errorArgs) => {
      this._handleConsoleError.call(this, ['error', ...errorArgs]);
    });

    const origConsoleError = console.error;
    window.console.error = (...errorArgs) => {
      this._handleConsoleError.call(this, ['error', ...errorArgs]);
      origConsoleError.apply(this, errorArgs);
    };

    const origConsoleLog = console.log;
    window.console.log = (...logArgs) => {
      this._handleConsoleError.call(this, ['log', ...logArgs]);
      origConsoleLog.apply(this, logArgs);
    };

    const origConsoleInfo = console.info;
    window.console.info = (...infoArgs) => {
      this._handleConsoleError.call(this, ['info', ...infoArgs]);
      origConsoleInfo.apply(this, infoArgs);
    };

    Request.registerHook(this._handleRequests);
  }

  _handleConsoleError(type, error, url, line) {
    if (typeof type === 'object' && type.length > 0) {
      this.messages.push({
        type: type[0],
        info: type,
      });
    } else {
      this.messages.push({
        type,
        error,
        url,
        line,
      });
    }
  }

  _handleRequests = action(async request => {
    if (request.isError) {
      this.error = request.error;

      if (request.error.json) {
        try {
          this.response = await request.error.json();
        } catch {
          this.response = {};
        }
        if (this.error.status === 401) {
          window['ferdi'].stores.app.authRequestFailed = true;
          // this.actions.user.logout({ serverLogout: true });
        }
      }

      this.messages.push({
        type: 'error',
        request: {
          result: request.result,
          wasExecuted: request.wasExecuted,
          method: request._method,
        },
        error: this.error,
        response: this.response,
        server: window['ferdi'].stores.settings.app.server,
      });
    } else {
      window['ferdi'].stores.app.authRequestFailed = false;
    }
  });
}