// errors.ts // Copyright (C) 2020 Dwayne Harris // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see . 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 } }