import { History } from 'history' import { setFieldNotification } from '../actions/forms' import { showNotification } from '../actions/notifications' import { AppThunkDispatch, FormNotification, NotificationType } from '../types' export function handleApiError(err: HttpError, dispatch: AppThunkDispatch, history?: History) { console.error('Error:', err) if (err instanceof ServerError) { dispatch(showNotification(NotificationType.Error, 'Server Error')) return } if (err instanceof BadRequestError) { dispatch(showNotification(NotificationType.Error, `Error: ${err.message}`)) for (const error of err.errors) { const { field, type, message } = error if (field) dispatch(setFieldNotification(field, type, message)) } return } if (err instanceof UnauthorizedError) { dispatch(showNotification(NotificationType.Error, 'You need to be logged in.')) if (history) history.push('/login') return } if (err instanceof NotFoundError) { dispatch(showNotification(NotificationType.Error, 'Not found.')) return } dispatch(showNotification(NotificationType.Error, `Error: ${err.message}`)) } export class HttpError extends Error { statusCode: number errors: FormNotification[] constructor(message = 'Unknown Error') { super(message) this.name = 'HttpError' this.statusCode = 500 this.errors = [] } } export class ServerError extends HttpError { constructor() { super('Server Error') this.name = 'ServerError' this.statusCode = 500 } } export class BadRequestError extends HttpError { constructor(message = 'Bad Request', errors: FormNotification[] = []) { super(message) this.name = 'BadRequestError' this.statusCode = 400 this.errors = errors } } export class UnauthorizedError extends HttpError { constructor(message = 'Unauthorized') { super(message) this.name = 'UnauthorizedError' this.statusCode = 401 } } export class ForbiddenError extends HttpError { constructor(message = 'Forbidden') { super(message) this.name = 'ForbiddenError' this.statusCode = 403 } } export class NotFoundError extends HttpError { constructor(message = 'Not Found') { super(message) this.name = 'NotFoundError' this.statusCode = 404 } }