0
# VError Class
1
2
The VError class is the primary error class that chains errors while preserving each error's message. It supports printf-style formatting, flexible constructor options, and provides a foundation for all other error classes in the library.
3
4
## Capabilities
5
6
### Constructor
7
8
Creates a VError instance with flexible argument patterns supporting different use cases.
9
10
```javascript { .api }
11
/**
12
* VError constructor with multiple signatures
13
* Can be called with or without 'new' keyword
14
*/
15
16
// Empty error
17
new VError();
18
19
// Printf-style message
20
new VError(message, ...printfArgs);
21
22
// Error with cause
23
new VError(causeError, message, ...printfArgs);
24
25
// Error with options
26
new VError(options, message, ...printfArgs);
27
28
/**
29
* Constructor options object
30
*/
31
interface VErrorOptions {
32
cause?: Error; // Underlying cause error
33
name?: string; // Error name override (default: 'VError')
34
info?: Object; // Additional structured metadata
35
skipCauseMessage?: boolean; // Skip appending cause message to this.message
36
strict?: boolean; // Force strict printf interpretation (like SError)
37
constructorOpt?: Function; // Constructor function for stack trace capture
38
}
39
```
40
41
**Usage Examples:**
42
43
```javascript
44
const VError = require('verror');
45
46
// Basic error
47
const err1 = new VError('something went wrong');
48
49
// Printf-style formatting
50
const err2 = new VError('failed to process file "%s"', filename);
51
52
// Error chaining
53
const err3 = new VError(originalError, 'operation failed');
54
55
// Full options
56
const err4 = new VError({
57
name: 'DatabaseError',
58
cause: dbError,
59
info: {
60
query: 'SELECT * FROM users',
61
table: 'users',
62
operation: 'select'
63
}
64
}, 'database query failed');
65
66
// Skip cause message in final message
67
const err5 = new VError({
68
cause: originalError,
69
skipCauseMessage: true
70
}, 'high-level operation failed');
71
```
72
73
### Instance Properties
74
75
Properties available on VError instances for accessing error information.
76
77
```javascript { .api }
78
interface VErrorInstance {
79
/** Error name, defaults to 'VError' or can be set via options */
80
name: string;
81
82
/** Complete error message including appended cause messages */
83
message: string;
84
85
/** Original short message without any cause messages appended */
86
jse_shortmsg: string;
87
88
/** Reference to the cause error, if provided */
89
jse_cause?: Error;
90
91
/** Additional information properties, shallow copy of options.info */
92
jse_info: Object;
93
94
/** Stack trace string */
95
stack: string;
96
}
97
```
98
99
### Instance Methods
100
101
Methods available on VError instances.
102
103
```javascript { .api }
104
/**
105
* Returns string representation of the error
106
* Format: "ErrorName: message"
107
* @returns {string} Formatted error string
108
*/
109
toString(): string;
110
111
/**
112
* Returns the cause error (compatibility method)
113
* NOTE: Returns undefined for no cause (use VError.cause() static method for null)
114
* @returns {Error|undefined} Cause error or undefined
115
*/
116
cause(): Error | undefined;
117
```
118
119
**Usage Examples:**
120
121
```javascript
122
const err = new VError({
123
name: 'ValidationError',
124
cause: originalError,
125
info: { field: 'email', value: 'invalid-email' }
126
}, 'validation failed for field "%s"', 'email');
127
128
console.log(err.name); // 'ValidationError'
129
console.log(err.message); // 'validation failed for field "email": original error message'
130
console.log(err.jse_shortmsg); // 'validation failed for field "email"'
131
console.log(err.jse_info); // { field: 'email', value: 'invalid-email' }
132
console.log(err.toString()); // 'ValidationError: validation failed for field "email": original error message'
133
console.log(err.cause()); // originalError instance
134
```
135
136
### Printf-Style Formatting
137
138
VError uses the `extsprintf` library for printf-style message formatting with special handling for null and undefined values.
139
140
```javascript { .api }
141
/**
142
* Printf-style formatting behavior:
143
* - %s: string formatting
144
* - %d: decimal number formatting
145
* - %j: JSON formatting
146
* - null/undefined: converted to "null"/"undefined" strings (non-strict mode)
147
* - strict option: forces strict interpretation, throws on null/undefined
148
*/
149
```
150
151
**Usage Examples:**
152
153
```javascript
154
// Basic formatting
155
new VError('user %s not found', userId);
156
new VError('invalid count: %d', count);
157
new VError('data: %j', { key: 'value' });
158
159
// Null/undefined handling (VError converts them by default)
160
new VError('value is %s', null); // "value is null"
161
new VError('value is %s', undefined); // "value is undefined"
162
163
// Strict mode throws on null/undefined
164
new VError({ strict: true }, 'user %s', 'john'); // OK
165
// new VError({ strict: true }, 'value is %s', null); // Throws error
166
167
// Multiple arguments
168
new VError('error in %s at line %d: %s', filename, lineNumber, details);
169
```
170
171
### Error Message Construction
172
173
How VError constructs the final error message from components.
174
175
```javascript { .api }
176
/**
177
* Message construction logic:
178
* 1. Format printf-style arguments into shortmessage
179
* 2. If cause exists and skipCauseMessage is false: shortmessage + ": " + cause.message
180
* 3. If cause exists and skipCauseMessage is true: shortmessage only
181
* 4. Final message is stored in this.message
182
*/
183
```
184
185
**Usage Examples:**
186
187
```javascript
188
const originalError = new Error('file not found');
189
190
// With cause message (default)
191
const err1 = new VError(originalError, 'failed to read config');
192
console.log(err1.message); // "failed to read config: file not found"
193
194
// Skip cause message
195
const err2 = new VError({
196
cause: originalError,
197
skipCauseMessage: true
198
}, 'failed to read config');
199
console.log(err2.message); // "failed to read config"
200
201
// Strict printf interpretation (like SError)
202
const err3 = new VError({ strict: true }, 'user %s not found', 'john'); // OK
203
// const err4 = new VError({ strict: true }, 'value is %s', null); // Would throw error
204
```
205
206
### Inheritance and Prototype
207
208
VError properly inherits from Error and can be extended.
209
210
```javascript { .api }
211
/**
212
* VError inheritance:
213
* - Inherits from Error using util.inherits()
214
* - Can be called without 'new' keyword
215
* - Supports Error.captureStackTrace when available
216
* - Can be subclassed for custom error types
217
*/
218
```
219
220
**Usage Examples:**
221
222
```javascript
223
const util = require('util');
224
225
// Can be called without 'new'
226
const err1 = VError('without new keyword');
227
228
// Custom error class
229
function CustomError() {
230
VError.apply(this, arguments);
231
}
232
util.inherits(CustomError, VError);
233
CustomError.prototype.name = 'CustomError';
234
235
const customErr = new CustomError('custom error occurred');
236
console.log(customErr instanceof VError); // true
237
console.log(customErr instanceof Error); // true
238
```