2019-12-08 00:32:00 +05:30
|
|
|
import { InternalServerError } from 'app/services/request';
|
|
|
|
import { Resp, Middleware } from 'app/services/request';
|
|
|
|
import defaultLogger from 'app/services/logger';
|
2019-12-07 16:58:52 +05:30
|
|
|
|
|
|
|
type Logger = typeof defaultLogger;
|
|
|
|
|
|
|
|
const ABORT_ERR = 20;
|
|
|
|
|
|
|
|
class BsodMiddleware implements Middleware {
|
2020-05-24 04:38:24 +05:30
|
|
|
dispatchBsod: () => any;
|
|
|
|
logger: Logger;
|
2019-12-07 16:58:52 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
constructor(dispatchBsod: () => any, logger: Logger = defaultLogger) {
|
|
|
|
this.dispatchBsod = dispatchBsod;
|
|
|
|
this.logger = logger;
|
2019-12-07 16:58:52 +05:30
|
|
|
}
|
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
async catch<T extends Resp<any>>(resp?: T | InternalServerError | Error): Promise<T> {
|
|
|
|
const { originalResponse } = (resp || {}) as InternalServerError;
|
|
|
|
|
|
|
|
if (
|
|
|
|
resp &&
|
|
|
|
((resp instanceof InternalServerError && (resp.error as any).code !== ABORT_ERR) ||
|
|
|
|
(originalResponse && /5\d\d/.test(originalResponse.status)))
|
|
|
|
) {
|
|
|
|
this.dispatchBsod();
|
|
|
|
|
|
|
|
const { message: errorMessage } = resp as { [key: string]: any };
|
|
|
|
|
|
|
|
if (!errorMessage || !/NetworkError/.test(errorMessage)) {
|
|
|
|
let message = 'Unexpected response (BSoD)';
|
|
|
|
|
|
|
|
if (errorMessage) {
|
|
|
|
message = `BSoD: ${errorMessage}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.logger.warn(message, { resp });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.reject(resp);
|
|
|
|
}
|
2019-12-07 16:58:52 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
export default BsodMiddleware;
|