All files / mgmt-lambda/handlers errorHandlers.ts

100% Statements 12/12
70% Branches 7/10
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          1x     1x                   5x         5x                           8x   8x 1x 7x 1x   8x                   4x     4x                
import type { APIGatewayProxyResult } from 'aws-lambda'
import { ErrorCode } from '../exceptions.ts'
import { ResourceNotFoundException } from '@aws-sdk/client-lambda'
 
export function handleNoAuthentication(): Promise<APIGatewayProxyResult> {
  const body = {
    status: 'Token is not specified or not valid',
  }
  return Promise.resolve({
    statusCode: 401,
    body: JSON.stringify(body),
    headers: {
      'content-type': 'application/json',
    },
  })
}
 
export function handleWrongConfiguration(error: unknown): Promise<APIGatewayProxyResult> {
  const body = {
    status:
      'Wrong function configuration. Check environment variables for Lambda@Edge function and CloudFront Distribution id',
    error: error instanceof Error ? error.message : error,
  }
  return Promise.resolve({
    statusCode: 500,
    body: JSON.stringify(body),
    headers: {
      'content-type': 'application/json',
    },
  })
}
 
type ErrorWithCode = Partial<Error> & {
  code?: ErrorCode
}
 
export function handleError(error: unknown): APIGatewayProxyResult {
  const errorWithCode: ErrorWithCode = error instanceof Error ? error : {}
 
  if (errorWithCode.name?.includes('AccessDenied') === true) {
    errorWithCode.code = ErrorCode.AWSAccessDenied
  } else if (errorWithCode.name === ResourceNotFoundException.name) {
    errorWithCode.code = ErrorCode.AWSResourceNotFound
  }
  return {
    statusCode: 500,
    body: JSON.stringify({ status: 'Error occurred', errorCode: errorWithCode.code ?? ErrorCode.UnknownError }),
    headers: {
      'content-type': 'application/json',
    },
  }
}
 
export function handleNotFound(): Promise<APIGatewayProxyResult> {
  const body = {
    status: 'Path not found',
  }
  return Promise.resolve({
    statusCode: 404,
    body: JSON.stringify(body),
    headers: {
      'content-type': 'application/json',
    },
  })
}