2018-03-24 09:54:19 +00:00
|
|
|
import { defineMessages } from 'react-intl';
|
2016-11-20 18:39:18 +00:00
|
|
|
import { showAlert } from '../actions/alerts';
|
2016-10-18 16:09:45 +01:00
|
|
|
|
|
|
|
const defaultFailSuffix = 'FAIL';
|
|
|
|
|
2018-03-24 09:54:19 +00:00
|
|
|
const messages = defineMessages({
|
|
|
|
unexpectedTitle: { id: 'alert.unexpected.title', defaultMessage: 'Oops!' },
|
|
|
|
unexpectedMessage: { id: 'alert.unexpected.message', defaultMessage: 'An unexpected error occurred.' },
|
|
|
|
});
|
|
|
|
|
2016-10-18 16:09:45 +01:00
|
|
|
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');
|
|
|
|
|
|
|
|
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-06-11 09:42:42 +01:00
|
|
|
console.error(action.error);
|
2018-03-24 09:54:19 +00:00
|
|
|
dispatch(showAlert(messages.unexpectedTitle, messages.unexpectedMessage));
|
2016-10-18 16:09:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(action);
|
|
|
|
};
|
|
|
|
};
|