# Error handling in Javascript  ```ts class NetworkError extends Error { constructor(message: string, options?: ErrorOptions) { super(message, options) this.name = 'NetworkError' } } class DatabaseError extends Error { constructor(message: string, options?: ErrorOptions) { super(message, options) this.name = 'DatabaseError' } } class APIError extends Error { constructor(message: string, options?: ErrorOptions) { super(message, options) this.name = 'APIError' } } function main() { try { try { try { throw new NetworkError('Failed to connect to server') } catch (err: unknown) { throw new DatabaseError('Failed to execute query', { cause: err }) } } catch (err: unknown) { throw new APIError('Failed to process request', { cause: err }) } } catch (err: unknown) { // ex. throw 42 if (!(err instanceof Error)) { console.log('unknown error') return } console.error(err) console.log(formatError(err)) } } main() function formatError(err: unknown): string { let messages: string[] = [] while (err instanceof Error) { messages.push(`${err.name}: ${err.message}`) err = err.cause } return messages.join(' → ') } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up