javascript / intermediate
Snippet
Custom Error Classes
Extending the built-in Error class allows you to create specialized error types for your application. This makes error handling more granular by allowing you to catch specific error types and attach additional metadata like error codes.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
class DatabaseError extends Error {constructor(message, code) {super(message);this.name = 'DatabaseError';this.code = code;}}try {throw new DatabaseError('Connection lost', 500);} catch (err) {console.error(`${err.name} [${err.code}]: ${err.message}`);}
Breakdown
1
class DatabaseError extends Error
Defines a new class that inherits all properties and methods of the native Error object.
2
super(message)
Calls the constructor of the parent Error class to properly initialize the error message property.