You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
2.2 KiB
88 lines
2.2 KiB
import { History } from 'history'
|
|
|
|
import { setFieldNotification } from 'src/actions/forms'
|
|
import { showNotification } from 'src/actions/notifications'
|
|
import { AppThunkDispatch, FormNotification } from 'src/types'
|
|
|
|
export function handleApiError(err: HttpError, dispatch: AppThunkDispatch, history: History) {
|
|
if (err instanceof ServerError) {
|
|
dispatch(showNotification('error', 'Server Error'))
|
|
}
|
|
|
|
if (err instanceof BadRequestError) {
|
|
dispatch(showNotification('error', `Error: ${err.message}`))
|
|
|
|
for (const error of err.errors) {
|
|
const { field, type, message } = error
|
|
if (field) dispatch(setFieldNotification(field, type, message))
|
|
}
|
|
}
|
|
|
|
if (err instanceof UnauthorizedError) {
|
|
dispatch(showNotification('error', 'You need to be logged in.'))
|
|
history.push('/login')
|
|
}
|
|
|
|
if (err instanceof NotFoundError) {
|
|
dispatch(showNotification('error', 'Not found.'))
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|