Skip to content

Commit

Permalink
[Feedback] Add option to queue flash messages to handleAPIError
Browse files Browse the repository at this point in the history
- Should be hopefully useful for calls that need to queue an error and then redirect to another page
  • Loading branch information
cee-chen committed Sep 11, 2020
1 parent ab889ee commit dcdd872
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
*/

jest.mock('./', () => ({
FlashMessagesLogic: { actions: { setFlashMessages: jest.fn() } },
FlashMessagesLogic: {
actions: {
setFlashMessages: jest.fn(),
setQueuedMessages: jest.fn(),
},
},
}));
import { FlashMessagesLogic } from './';

Expand Down Expand Up @@ -37,6 +42,16 @@ describe('handleAPIError', () => {
]);
});

it('queues messages when isQueued is passed', () => {
handleAPIError(mockHttpError, { isQueued: true });

expect(FlashMessagesLogic.actions.setQueuedMessages).toHaveBeenCalledWith([
{ type: 'error', message: 'Could not find X' },
{ type: 'error', message: 'Could not find Y' },
{ type: 'error', message: 'Something else bad happened' },
]);
});

it('displays a generic error message and re-throws non-API errors', () => {
try {
handleAPIError(Error('whatever') as any);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,28 @@ interface IErrorResponse {
errors: string[];
};
}
interface IOptions {
isQueued?: boolean;
}

/**
* Converts API/HTTP errors into user-facing Flash Messages
*/
export const handleAPIError = (error: HttpResponse<IErrorResponse>) => {
export const handleAPIError = (
error: HttpResponse<IErrorResponse>,
{ isQueued }: IOptions = {}
) => {
const defaultErrorMessage = 'An unexpected error occurred';

const errorFlashMessages: IFlashMessage[] = Array.isArray(error?.body?.attributes?.errors)
? error.body!.attributes.errors.map((message) => ({ type: 'error', message }))
: [{ type: 'error', message: defaultErrorMessage }];

FlashMessagesLogic.actions.setFlashMessages(errorFlashMessages);
if (isQueued) {
FlashMessagesLogic.actions.setQueuedMessages(errorFlashMessages);
} else {
FlashMessagesLogic.actions.setFlashMessages(errorFlashMessages);
}

// If this was a programming error or a failed request (such as a CORS) error,
// we rethrow the error so it shows up in the developer console
Expand Down

0 comments on commit dcdd872

Please sign in to comment.