File size: 1,511 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
export const HTTPAccessErrorStatus = {
  NOT_FOUND: 404,
  FORBIDDEN: 403,
  UNAUTHORIZED: 401,
}

const ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))

export const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'

export type HTTPAccessFallbackError = Error & {
  digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`
}

/**
 * Checks an error to determine if it's an error generated by
 * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.
 *
 * @param error the error that may reference a HTTP access error
 * @returns true if the error is a HTTP access error
 */
export function isHTTPAccessFallbackError(
  error: unknown
): error is HTTPAccessFallbackError {
  if (
    typeof error !== 'object' ||
    error === null ||
    !('digest' in error) ||
    typeof error.digest !== 'string'
  ) {
    return false
  }
  const [prefix, httpStatus] = error.digest.split(';')

  return (
    prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&
    ALLOWED_CODES.has(Number(httpStatus))
  )
}

export function getAccessFallbackHTTPStatus(
  error: HTTPAccessFallbackError
): number {
  const httpStatus = error.digest.split(';')[1]
  return Number(httpStatus)
}

export function getAccessFallbackErrorTypeByStatus(
  status: number
): 'not-found' | 'forbidden' | 'unauthorized' | undefined {
  switch (status) {
    case 401:
      return 'unauthorized'
    case 403:
      return 'forbidden'
    case 404:
      return 'not-found'
    default:
      return
  }
}