File size: 2,338 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { NoticeMessage } from '../../../index.js'
import { ActionContext, BulkActionResponse, RecordActionResponse } from '../../actions/action.interface.js'
import AppError from '../../utils/errors/app-error.js'
import ForbiddenError from '../../utils/errors/forbidden-error.js'
import NotFoundError from '../../utils/errors/not-found-error.js'
import RecordError from '../../utils/errors/record-error.js'
import ValidationError, { PropertyErrors } from '../../utils/errors/validation-error.js'

/**
 * @private
 * @classdesc
 * Function which catches all the errors thrown by the action hooks or handler
 */
const actionErrorHandler = (
  error: Error,
  context: ActionContext,
): RecordActionResponse | BulkActionResponse => {
  if (
    error instanceof ValidationError
    || error instanceof ForbiddenError
    || error instanceof NotFoundError
    || error instanceof AppError
  ) {
    const { record, currentAdmin, action } = context

    const baseError: RecordError | null = error.baseError ?? null
    let baseMessage = ''
    let errors: PropertyErrors = {}
    let meta: any
    let notice: NoticeMessage
    if (error instanceof ValidationError) {
      baseMessage = error.baseError?.message
        || 'thereWereValidationErrors'
      errors = error.propertyErrors
    } else {
      // ForbiddenError, NotFoundError, AppError
      baseMessage = error.baseMessage
        || 'anyForbiddenError'
    }

    // Add required meta data for the list action
    if (action.name === 'list') {
      meta = {
        total: 0,
        perPage: 0,
        page: 0,
        direction: null,
        sortBy: null,
      }
    }

    const recordJson = record?.toJSON?.(currentAdmin)

    if (error instanceof ForbiddenError && recordJson) {
      recordJson.params = {}
      recordJson.title = ''
      recordJson.populated = {}
    }

    notice = {
      message: baseMessage,
      type: 'error',
    }

    if (error instanceof AppError && error.notice) {
      notice = {
        ...notice,
        ...error.notice,
      }
    }

    return {
      record: {
        ...recordJson,
        params: recordJson?.params ?? {},
        populated: recordJson?.populated ?? {},
        baseError,
        errors,
      },
      records: [],
      notice,
      meta,
    }
  }
  throw error
}

export default actionErrorHandler