-
Notifications
You must be signed in to change notification settings - Fork 69
/
sfdxError.ts
321 lines (283 loc) · 8.86 KB
/
sfdxError.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { NamedError } from '@salesforce/kit';
import { ensure, hasString, isString, JsonMap, Optional } from '@salesforce/ts-types';
import { Messages, Tokens } from './messages';
/**
* A class to manage all the keys and tokens for a message bundle to use with SfdxError.
*
* ```
* SfdxError.create(new SfdxErrorConfig('MyPackage', 'apex', 'runTest').addAction('apexErrorAction1', [className]));
* ```
*/
export class SfdxErrorConfig {
/**
* The name of the package
*/
public readonly packageName: string;
/**
* The name of the bundle
*/
public readonly bundleName: string;
/**
* The error key
*/
public errorKey: string;
private errorTokens: Tokens;
private messages?: Messages;
private actions = new Map<string, Tokens>();
/**
* Create a new SfdxErrorConfig.
*
* @param packageName The name of the package.
* @param bundleName The message bundle.
* @param errorKey The error message key.
* @param errorTokens The tokens to use when getting the error message.
* @param actionKey The action message key.
* @param actionTokens The tokens to use when getting the action message(s).
*/
public constructor(
packageName: string,
bundleName: string,
errorKey: string,
errorTokens: Tokens = [],
actionKey?: string,
actionTokens?: Tokens
) {
this.packageName = packageName;
this.bundleName = bundleName;
this.errorKey = errorKey;
this.errorTokens = errorTokens;
if (actionKey) this.addAction(actionKey, actionTokens);
}
/**
* Set the error key.
*
* @param key The key to set.
* @returns {SfdxErrorConfig} For convenience `this` object is returned.
*/
public setErrorKey(key: string): SfdxErrorConfig {
this.errorKey = key;
return this;
}
/**
* Set the error tokens.
*
* @param tokens The tokens to set. For convenience `this` object is returned.
*/
public setErrorTokens(tokens: Tokens): SfdxErrorConfig {
this.errorTokens = tokens;
return this;
}
/**
* Add an error action to assist the user with a resolution. For convenience `this` object is returned.
*
* @param actionKey The action key in the message bundle.
* @param actionTokens The action tokens for the string.
*/
public addAction(actionKey: string, actionTokens: Tokens = []): SfdxErrorConfig {
this.actions.set(actionKey, actionTokens);
return this;
}
/**
* Load the messages using `Messages.loadMessages`. Returns the loaded messages.
*/
public load(): Messages {
this.messages = Messages.loadMessages(this.packageName, this.bundleName);
return this.messages;
}
/**
* Get the error message using messages.getMessage.
* **Throws** If `errorMessages.load` was not called first.
*/
public getError(): string {
if (!this.messages) {
throw new SfdxError('SfdxErrorConfig not loaded.');
}
return this.messages.getMessage(this.errorKey, this.errorTokens);
}
/**
* Get the action messages using messages.getMessage.
* **@throws** If `errorMessages.load` was not called first.
*/
public getActions(): Optional<string[]> {
if (!this.messages) {
throw new SfdxError('SfdxErrorConfig not loaded.');
}
if (this.actions.size === 0) return;
const actions: string[] = [];
this.actions.forEach((tokens, key) => {
const messages = this.messages;
if (messages) {
actions.push(messages.getMessage(key, tokens));
}
});
return actions;
}
/**
* Remove all actions from this error config. Useful when reusing SfdxErrorConfig for other error messages within
* the same bundle. For convenience `this` object is returned.
*/
public removeActions(): SfdxErrorConfig {
this.actions = new Map();
return this;
}
}
/**
* A generalized sfdx error which also contains an action. The action is used in the
* CLI to help guide users past the error.
*
* To throw an error in a synchronous function you must either pass the error message and actions
* directly to the constructor, e.g.
*
* ```
* // To load a message bundle:
* Messages.importMessagesDirectory(__dirname);
* this.messages = Messages.loadMessages('myPackageName', 'myBundleName');
* // Note that __dirname should contain a messages folder.
*
* // To throw an error associated with the message from the bundle:
* throw SfdxError.create('myPackageName', 'myBundleName', 'MyErrorMessageKey', [messageToken1]);
*
* // To throw a non-bundle based error:
* throw new SfdxError(myErrMsg, 'MyErrorName');
* ```
*/
export class SfdxError extends NamedError {
/**
* The message string. Error.message
*/
public message!: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public name: any;
/**
* Action messages. Hints to the users regarding what can be done to fix related issues.
*/
public actions?: string[];
/**
* SfdxCommand can return this process exit code.
*/
public exitCode: number;
/**
* The related command name for this error.
*/
public commandName?: string;
// Additional data helpful for consumers of this error. E.g., API call result
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public data: any;
/**
* Some errors support `error.code` instead of `error.name`. This keeps backwards compatability.
*/
private _code?: string;
/**
* Create an SfdxError.
*
* @param message The error message.
* @param name The error name. Defaults to 'SfdxError'.
* @param actions The action message(s).
* @param exitCode The exit code which will be used by SfdxCommand.
* @param cause The underlying error that caused this error to be raised.
*/
public constructor(message: string, name?: string, actions?: string[], exitCode?: number, cause?: Error) {
super(name || 'SfdxError', message, cause);
this.actions = actions;
this.exitCode = exitCode || 1;
}
/**
* Create a new `SfdxError`.
*
* @param packageName The message package name used to create the `SfdxError`.
* @param bundleName The message bundle name used to create the `SfdxError`.
* @param key The key within the bundle for the message.
* @param tokens The values to use for message tokenization.
*/
public static create(packageName: string, bundleName: string, key: string, tokens?: Tokens): SfdxError;
/**
* Create a new SfdxError.
*
* @param errorConfig The `SfdxErrorConfig` object used to create the SfdxError.
*/
public static create(errorConfig: SfdxErrorConfig): SfdxError;
// The create implementation function.
public static create(
nameOrConfig: string | SfdxErrorConfig,
bundleName?: string,
key?: string,
tokens?: Tokens
): SfdxError {
let errorConfig: SfdxErrorConfig;
if (isString(nameOrConfig)) {
errorConfig = new SfdxErrorConfig(nameOrConfig, ensure(bundleName), ensure(key), tokens);
} else {
errorConfig = nameOrConfig;
}
errorConfig.load();
return new SfdxError(errorConfig.getError(), errorConfig.errorKey, errorConfig.getActions());
}
/**
* Convert an Error to an SfdxError.
*
* @param err The error to convert.
*/
public static wrap(err: Error | string): SfdxError {
if (isString(err)) {
return new SfdxError(err);
}
const sfdxError = new SfdxError(err.message, err.name);
if (sfdxError.stack) {
sfdxError.stack = sfdxError.stack.replace(`${err.name}: ${err.message}`, 'Outer stack:');
sfdxError.stack = `${err.stack}\n${sfdxError.stack}`;
}
// If the original error has a code, use that instead of name.
if (hasString(err, 'code')) {
sfdxError.code = err.code;
}
return sfdxError;
}
public get code() {
return this._code || this.name;
}
public set code(code: string) {
this._code = code;
}
/**
* Sets the name of the command. For convenience `this` object is returned.
*
* @param commandName The command name.
*/
public setCommandName(commandName: string): SfdxError {
this.commandName = commandName;
return this;
}
/**
* An additional payload for the error. For convenience `this` object is returned.
*
* @param data The payload data.
*/
public setData(data: unknown): SfdxError {
this.data = data;
return this;
}
/**
* Convert an {@link SfdxError} state to an object. Returns a plain object representing the state of this error.
*/
public toObject(): JsonMap {
const obj: JsonMap = {
name: this.name,
message: this.message || this.name,
exitCode: this.exitCode,
actions: this.actions,
};
if (this.commandName) {
obj.commandName = this.commandName;
}
if (this.data) {
obj.data = this.data;
}
return obj;
}
}