Skip to content

Instantly share code, notes, and snippets.

@sidola
Last active November 9, 2020 20:31
Show Gist options
  • Save sidola/5853567ffc2d31e3063722f6e060ac07 to your computer and use it in GitHub Desktop.
Save sidola/5853567ffc2d31e3063722f6e060ac07 to your computer and use it in GitHub Desktop.
TS Custom Error
export class UnknownError extends Error {
get name() { return this.constructor.name }
public detail: Readonly<string>
public error: Readonly<Error> | undefined
constructor({ detail, error }: { detail: string, error?: Error }) {
super(
`Unknown error occurred, detail: ${detail}, `
+ `inner error: ${error?.message ?? 'none-given'}`
)
this.detail = detail
this.error = error
}
}
export class NotFoundError extends Error {
get name() { return this.constructor.name }
public resourceName: Readonly<string>
constructor({ resourceName }: { resourceName: string }) {
super(`${resourceName} not found`)
this.resourceName = resourceName
}
}
type XhrResponseErrorParams = {
httpStatus: number
url: string
detail: string
headers: {
[key: string]: string
}
}
export class XhrResponseError extends Error {
get name() { return this.constructor.name }
public httpStatus: Readonly<number>
public url: Readonly<string>
public headers: Readonly<{ [key: string]: string }>
public detail: Readonly<string>
constructor({ httpStatus, url, detail, headers }: XhrResponseErrorParams) {
super(
`XHR Error occurred\n\n` +
`URL: ${url}\n` +
`Status: ${httpStatus}\n\n` +
`Detail: ${detail}`
)
this.httpStatus = httpStatus
this.url = url
this.detail = detail
this.headers = headers
}
}
export class XhrRequestError extends Error {
get name() { return this.constructor.name }
public url: Readonly<string>
constructor({ url }: { url: string }) {
super(
`XHR Error occurred, request failed\n\n` +
`URL: ${url}\n`
)
this.url = url
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment