0
# Error Handling
1
2
Specialized error handling for CLI operations with user-friendly messages and proper exit codes, designed to provide clear feedback for common CLI usage issues.
3
4
## Capabilities
5
6
### Pretty Error Class
7
8
Custom error class for user-friendly CLI error messages with proper stack trace handling.
9
10
```typescript { .api }
11
/**
12
* Custom error class for user-friendly CLI error messages
13
* Extends standard Error with proper stack trace capture
14
*/
15
class PrettyError extends Error {
16
/**
17
* Creates a new PrettyError with user-friendly message
18
* @param message - Human-readable error message to display
19
*/
20
constructor(message: string);
21
}
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
// Note: PrettyError may not be directly exported from main package entry
28
import { PrettyError } from "@unocss/cli";
29
30
// Throw user-friendly error
31
function validateInput(patterns: string[]) {
32
if (!patterns || patterns.length === 0) {
33
throw new PrettyError(
34
"No glob patterns provided, try unocss <path/to/**/*>"
35
);
36
}
37
}
38
39
// Handle in try-catch
40
try {
41
validateInput([]);
42
} catch (error) {
43
if (error instanceof PrettyError) {
44
console.error("Configuration error:", error.message);
45
}
46
}
47
```
48
49
### Global Error Handler
50
51
Global error handler for CLI operations that manages process exit codes and user feedback.
52
53
```typescript { .api }
54
/**
55
* Global error handler for CLI operations
56
* Sets process exit code and logs appropriate error messages
57
* @param error - Error to handle (PrettyError or generic error)
58
*/
59
function handleError(error: unknown): void;
60
```
61
62
**Usage Examples:**
63
64
```typescript
65
// Note: handleError may not be directly exported from main package entry
66
import { handleError, build } from "@unocss/cli";
67
68
// Handle build errors gracefully
69
async function runBuild() {
70
try {
71
await build({
72
patterns: ["src/**/*.html"],
73
outFile: "dist/styles.css",
74
});
75
} catch (error) {
76
handleError(error);
77
// Process will exit with code 1
78
}
79
}
80
81
// Use as global handler
82
process.on('unhandledRejection', handleError);
83
process.on('uncaughtException', handleError);
84
```
85
86
## Error Types and Scenarios
87
88
### Configuration Errors
89
90
Common configuration-related errors and their messages:
91
92
```typescript
93
// Missing patterns
94
throw new PrettyError(
95
"No glob patterns, try unocss <path/to/**/*>"
96
);
97
98
// Invalid output configuration (logged as fatal, doesn't throw)
99
// consola.fatal("Cannot use --stdout and --out-file at the same time")
100
// Function returns early without throwing
101
102
// Configuration file not found
103
throw new PrettyError(
104
"Configuration file not found: uno.config.js"
105
);
106
```
107
108
### File System Errors
109
110
File system related errors are handled gracefully:
111
112
```typescript
113
// File permission errors
114
try {
115
await fs.writeFile(outFile, css, 'utf-8');
116
} catch (error) {
117
throw new PrettyError(
118
`Cannot write to output file: ${outFile}. Check permissions.`
119
);
120
}
121
122
// Directory creation errors
123
try {
124
await fs.mkdir(dir, { recursive: true });
125
} catch (error) {
126
throw new PrettyError(
127
`Cannot create output directory: ${dir}`
128
);
129
}
130
```
131
132
### UnoCSS Processing Errors
133
134
Errors during CSS generation are wrapped for better user experience:
135
136
```typescript
137
// Token processing errors
138
try {
139
const { css } = await ctx.uno.generate(tokens);
140
} catch (error) {
141
throw new PrettyError(
142
`CSS generation failed: ${error.message}`
143
);
144
}
145
146
// Transformer errors
147
try {
148
const result = await applyTransformers(ctx, code, id);
149
} catch (error) {
150
throw new PrettyError(
151
`Transformer processing failed for ${id}: ${error.message}`
152
);
153
}
154
```
155
156
## Error Handling Patterns
157
158
### CLI Error Handling
159
160
The CLI startup process includes comprehensive error handling:
161
162
```typescript
163
import { startCli, handleError } from "@unocss/cli";
164
165
// CLI entry point with error handling
166
startCli().catch(handleError);
167
```
168
169
### Programmatic Error Handling
170
171
When using the programmatic API, errors should be handled appropriately:
172
173
```typescript
174
import { build, PrettyError, handleError } from "@unocss/cli";
175
176
async function safeBuild(options: CliOptions) {
177
try {
178
await build(options);
179
console.log("✅ Build completed successfully");
180
} catch (error) {
181
if (error instanceof PrettyError) {
182
// User-friendly error - log and exit gracefully
183
console.error("❌ Build failed:", error.message);
184
process.exit(1);
185
} else {
186
// Unexpected error - use global handler
187
handleError(error);
188
}
189
}
190
}
191
```
192
193
### Watch Mode Error Handling
194
195
File watching includes error recovery mechanisms:
196
197
```typescript
198
// Watcher error handling
199
watcher.on('error', (error) => {
200
console.error('File watcher error:', error.message);
201
// Watcher continues running for other files
202
});
203
204
// Configuration reload error handling
205
try {
206
await ctx.reloadConfig();
207
} catch (error) {
208
console.error('Configuration reload failed:', error.message);
209
// Falls back to previous configuration
210
}
211
```
212
213
## Error Recovery
214
215
The CLI includes several error recovery mechanisms:
216
217
### Graceful Degradation
218
219
- **Configuration errors**: Falls back to default configuration
220
- **File permission errors**: Continues processing other files
221
- **Transformer errors**: Skips problematic transformers
222
- **Watch errors**: Continues monitoring other files
223
224
### User Guidance
225
226
Error messages include actionable guidance:
227
228
- **Missing patterns**: Suggests correct usage syntax
229
- **Permission errors**: Indicates file permission requirements
230
- **Configuration errors**: Points to configuration file issues
231
- **Output conflicts**: Explains conflicting options
232
233
### Process Management
234
235
- **Exit codes**: Sets appropriate exit codes for different error types
236
- **Signal handling**: Gracefully shuts down watchers on process termination
237
- **Resource cleanup**: Ensures file handles and watchers are properly closed