---
# System prepended metadata

title: Error handling in Javascript

---

# Error handling in Javascript

![截圖 2025-02-12 下午2.45.11](https://hackmd.io/_uploads/BkmF7aYtke.png)


```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(' → ')
}

```