Utility functions for WebPieces - works in browser and Node.js
npm install @webpieces/core-utilUtility functions for WebPieces applications. Works in both browser and Node.js environments.
``bash`
npm install @webpieces/core-util
The toError() function converts any thrown value into a proper Error instance.
#### Usage
`typescript
import { toError } from '@webpieces/core-util';
try {
await riskyOperation();
} catch (err: any) {
const error = toError(err);
console.error('Operation failed:', error.message);
throw error;
}
`
#### Why use toError()?
JavaScript allows throwing any value, not just Errors:
- throw "string error" - loses stack tracethrow { code: 404 }
- - not an Error instancethrow null
- - extremely unhelpful
toError() ensures you always have a proper Error object with:
- Type safety (always returns Error)
- Stack traces preserved when available
- Consistent error structure
- Integration with logging/monitoring
#### Enforced Pattern
WebPieces projects enforce this pattern via ESLint rule @webpieces/catch-error-pattern:
Required:
`typescript`
try {
operation();
} catch (err: any) {
const error = toError(err);
// Handle error...
}
Alternative (explicitly ignored errors):
`typescript`
try {
operation();
} catch (err: any) {
//const error = toError(err);
}
#### Nested Catch Blocks
For nested catches, use numbered suffixes:
`typescript`
try {
operation1();
} catch (err: any) {
const error = toError(err);
try {
rollback();
} catch (err2: any) {
const error2 = toError(err2);
console.error('Rollback failed:', error2);
}
}
#### Behavior
| Input Type | Behavior | Example |
|------------|----------|---------|
| Error instance | Returned unchanged | toError(new Error('msg')) → same Error |toError({message: 'msg', stack: '...'})
| Error-like object | Converts to Error, preserves message/name/stack | |toError({code: 404})
| Object without message | Stringifies object | → Error("Non-Error object thrown: {...}") |toError("error")
| String | Wraps in Error | → Error("error") |toError(404)
| Number | Converts to string | → Error("404") |toError(null)
| null/undefined | Generic message | → Error("Null or undefined thrown")` |
This package has zero dependencies and works in all modern browsers and Node.js environments.
- @webpieces/dev-config - Includes ESLint rule that enforces this pattern
- @webpieces/core-context - Request context management
- @webpieces/http-server - HTTP server
Apache-2.0