2016-11-20 18:39:18 +00:00
|
|
|
import { showAlert } from '../actions/alerts';
|
2016-10-18 16:09:45 +01:00
|
|
|
|
2016-11-22 21:59:54 +00:00
|
|
|
const defaultSuccessSuffix = 'SUCCESS';
|
2016-10-18 16:09:45 +01:00
|
|
|
const defaultFailSuffix = 'FAIL';
|
|
|
|
|
|
|
|
export default function errorsMiddleware() {
|
|
|
|
return ({ dispatch }) => next => action => {
|
2017-02-26 22:06:27 +00:00
|
|
|
if (action.type && !action.skipAlert) {
|
2016-10-18 16:09:45 +01:00
|
|
|
const isFail = new RegExp(`${defaultFailSuffix}$`, 'g');
|
2016-11-22 21:59:54 +00:00
|
|
|
const isSuccess = new RegExp(`${defaultSuccessSuffix}$`, 'g');
|
2016-10-18 16:09:45 +01:00
|
|
|
|
|
|
|
if (action.type.match(isFail)) {
|
|
|
|
if (action.error.response) {
|
|
|
|
const { data, status, statusText } = action.error.response;
|
|
|
|
|
|
|
|
let message = statusText;
|
|
|
|
let title = `${status}`;
|
|
|
|
|
|
|
|
if (data.error) {
|
|
|
|
message = data.error;
|
|
|
|
}
|
|
|
|
|
2016-11-20 18:39:18 +00:00
|
|
|
dispatch(showAlert(title, message));
|
2016-10-18 16:09:45 +01:00
|
|
|
} else {
|
2017-04-15 12:27:27 +01:00
|
|
|
console.error(action.error); // eslint-disable-line no-console
|
2017-01-05 02:31:45 +00:00
|
|
|
dispatch(showAlert('Oops!', 'An unexpected error occurred.'));
|
2016-10-18 16:09:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(action);
|
|
|
|
};
|
|
|
|
};
|