Skip to content
This repository was archived by the owner on Feb 9, 2024. It is now read-only.
This repository was archived by the owner on Feb 9, 2024. It is now read-only.

Handling Errors  #59

@exvuma

Description

@exvuma

Proposal on how to fix issues like #44

Custom Error class

I suggest we create a custom error class that looks something like

export class KVError extends Error {
  constructor(message?: string, code: number = 500) {
    super(message)
    Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
    this.name = KVError.name // stack traces display correctly now
    this.code = code
  }
  code: number // Appropriate HTTP status code
}

getAssetFromKV throws custom error

getAssetFromKV will now throw custom errors that we can identify as KVError.

Example inside getAssetFromKV

    throw new KVError(`${request.method} is not a valid request method`, 405)
    throw new KVError(`there is no ${ASSET_NAMESPACE} namespace bound to the script`, 500)

Workers sites template

now instead of having crazy try/catch blocks and assuming a 404 error in the sites template, we'd have workers-site-template look like:

try {
  let resp = await getAssetFromKV()
  return new Response(resp.message, { status: resp.code })
} catch (e) {
  if (resp instanceof KVError) {
    switch (e.code) {
      case 404:
        return notFoundResponse
        break
      case 401:
        return methodNotAllowedResponse
        break
      default:
        return new Response(resp.message, { status: resp.code })
    }
  }
}

Alternative option: getAssetFromKV returns a custom error

getAssetFromKV will now not throw generated errors, but instead optionally return KVError.

const getAssetFromKV: (event..) => Promise<KVError | Response>

Examples of returning these errors instead of throwing them:

    return new KVError(`${request.method} is not a valid request method`, 405)
    return new KVError(`there is no ${ASSET_NAMESPACE} namespace bound to the script`, 500)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions