2016-11-21 05:39:18 +11:00
|
|
|
import { showAlert } from '../actions/alerts';
|
2016-10-19 02:09:45 +11:00
|
|
|
|
2016-11-23 08:59:54 +11:00
|
|
|
const defaultSuccessSuffix = 'SUCCESS';
|
2016-10-19 02:09:45 +11:00
|
|
|
const defaultFailSuffix = 'FAIL';
|
|
|
|
|
|
|
|
export default function errorsMiddleware() {
|
|
|
|
return ({ dispatch }) => next => action => {
|
2017-02-27 09:06:27 +11:00
|
|
|
if (action.type && !action.skipAlert) {
|
2016-10-19 02:09:45 +11:00
|
|
|
const isFail = new RegExp(`${defaultFailSuffix}$`, 'g');
|
2016-11-23 08:59:54 +11:00
|
|
|
const isSuccess = new RegExp(`${defaultSuccessSuffix}$`, 'g');
|
2016-10-19 02:09:45 +11: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-21 05:39:18 +11:00
|
|
|
dispatch(showAlert(title, message));
|
2016-10-19 02:09:45 +11:00
|
|
|
} else {
|
2017-06-11 18:42:42 +10:00
|
|
|
console.error(action.error);
|
2017-01-05 13:31:45 +11:00
|
|
|
dispatch(showAlert('Oops!', 'An unexpected error occurred.'));
|
2016-10-19 02:09:45 +11:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(action);
|
|
|
|
};
|
|
|
|
};
|