Merge pull request #10 from overleaf/v3

Rework to favor tagging over wrapping
This commit is contained in:
John Lees-Miller 2020-05-15 14:53:24 +01:00 committed by GitHub
commit 676bdb794b
15 changed files with 2346 additions and 355 deletions

View file

@ -11,6 +11,7 @@ jobs:
steps:
- run: npm install
- run: npm run lint
- run: npm run typecheck
- run: npm test
workflows:
build-and-test:

View file

@ -17,9 +17,6 @@
"files": ["test/**/*.js"],
"env": {
"mocha": true
},
"globals": {
"expect": "readonly"
}
}
]

View file

@ -1,96 +1,424 @@
# @overleaf/o-error
[![npm version](https://badge.fury.io/js/%40overleaf%2Fo-error.svg)](https://badge.fury.io/js/%40overleaf%2Fo-error)
[![CircleCI](https://circleci.com/gh/overleaf/o-error.svg?style=svg)](https://circleci.com/gh/overleaf/o-error)
Make custom error classes that:
Light-weight helpers for handling JavaScript Errors in node.js and the browser.
- pass `instanceof` checks,
- have stack traces,
- support custom messages and properties (`info`), and
- can wrap internal errors (causes) like [VError](https://github.com/joyent/node-verror).
- Get long stack traces across async functions and callbacks with `OError.tag`.
- Easily make custom `Error` subclasses.
- Wrap internal errors, preserving the original errors for logging as `causes`.
- Play nice with error logging services by keeping data in attached `info` objects instead of the error message.
ES6 classes make it easy to define custom errors by subclassing `Error`. Subclassing `OError` adds a few extra helpers.
## Table of Contents
## Usage
<!-- toc -->
### Throw an error directly
- [Long Stack Traces with `OError.tag`](#long-stack-traces-with-oerrortag)
* [The Problem](#the-problem)
* [The Solution](#the-solution)
* [Adding More Info](#adding-more-info)
* [`async`/`await`](#asyncawait)
* [Better Async Stack Traces in Node 12+](#better-async-stack-traces-in-node-12)
- [Create Custom Error Classes](#create-custom-error-classes)
* [Attaching Extra Info](#attaching-extra-info)
* [Wrapping an Internal Error](#wrapping-an-internal-error)
- [OError API Reference](#oerror-api-reference)
* [new OError(message, [info], [cause])](#new-oerrormessage-info-cause)
* [oError.withInfo(info) ⇒ this](#oerrorwithinfoinfo--this)
* [oError.withCause(cause) ⇒ this](#oerrorwithcausecause--this)
* [OError.tag(error, [message], [info]) ⇒ Error](#oerrortagerror-message-info--error)
* [OError.getFullInfo(error) ⇒ Object](#oerrorgetfullinfoerror--object)
* [OError.getFullStack(error) ⇒ string](#oerrorgetfullstackerror--string)
- [References](#references)
<!-- tocstop -->
## Long Stack Traces with `OError.tag`
### The Problem
While JavaScript errors have stack traces, they only go back to the start of the latest tick, so they are often not very useful. For example:
```js
const OError = require('@overleaf/o-error')
const demoDatabase = {
findUser(id, callback) {
process.nextTick(() => {
// return result asynchronously
if (id === 42) {
callback(null, { name: 'Bob' })
} else {
callback(new Error('not found'))
}
})
},
}
function doSomethingBad() {
throw new OError({
message: 'did something bad',
info: { thing: 'foo' },
function sayHi1(userId, callback) {
demoDatabase.findUser(userId, (err, user) => {
if (err) return callback(err)
callback(null, 'Hi ' + user.name)
})
}
doSomethingBad()
// =>
// { OError: did something bad
// at doSomethingBad (repl:2:9) <-- stack trace
// name: 'OError', <-- default name
// info: { thing: 'foo' } } <-- attached info
```
### Custom error class
```js
class FooError extends OError {
constructor(options) {
super({ message: 'failed to foo', ...options })
sayHi1(43, (err, result) => {
if (err) {
console.error(err)
} else {
console.log(result)
}
}
function doFoo() {
throw new FooError({ info: { foo: 'bar' } })
}
doFoo()
// =>
// { FooError: failed to foo
// at doFoo (repl:2:9) <-- stack trace
// name: 'FooError', <-- correct name
// info: { foo: 'bar' } } <-- attached info
})
```
### Wrapping an inner error (cause)
The resulting error's stack trace doesn't make any mention of our `sayHi1` function; it starts at the `nextTick` built-in:
```
Error: not found
at process.nextTick (repl:8:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
```
In practice, it's often even worse, like
```
DBError: socket connection refused
at someObscureLibraryFunction (...)
at ...
```
### The Solution
Before passing the error to a callback, call the `OError.tag` function to capture a stack trace at the call site:
```js
function doFoo2() {
const OError = require('.')
function sayHi2(userId, callback) {
demoDatabase.findUser(userId, (err, user) => {
if (err) return callback(OError.tag(err))
callback(null, 'Hi ' + user.name)
})
}
sayHi2(43, (err, result) => {
if (err) {
console.error(OError.getFullStack(OError.tag(err)))
} else {
console.log(result)
}
})
```
And use `OError.getFullStack` to reconstruct the full stack, including the tagged errors:
```
Error: not found
at process.nextTick (repl:8:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
TaggedError
at demoDatabase.findUser (repl:3:37)
at process.nextTick (repl:8:9)
at process._tickCallback (internal/process/next_tick.js:61:11)
TaggedError
at sayHi2 (repl:3:46)
at demoDatabase.findUser (repl:3:21)
at process.nextTick (repl:8:9)
at process._tickCallback (internal/process/next_tick.js:61:11)
```
The full stack contains the original error's stack and also the `TaggedError` stacks. There's some redundancy, but it's better to have too much information than too little.
### Adding More Info
You can add more information at each `tag` call site: a message and an `info` object with custom properties.
```js
function sayHi3(userId, callback) {
demoDatabase.findUser(userId, (err, user) => {
if (err) return callback(OError.tag(err, 'failed to find user', { userId }))
callback(null, 'Hi ' + user.name)
})
}
sayHi3(43, (err, result) => {
if (err) {
OError.tag(err, 'failed to say hi')
console.error(OError.getFullStack(err))
console.error(OError.getFullInfo(err))
} else {
console.log(result)
}
})
```
The `OError.getFullInfo` property merges all of the `info`s from the tags together into one object. This logs a full stack trace with `failed to ...` annotations and an `info` object that contains the `userId` that it failed to find:
```
Error: not found
at process.nextTick (repl:8:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
TaggedError: failed to find user
at demoDatabase.findUser (repl:3:37)
at process.nextTick (repl:8:9)
at process._tickCallback (internal/process/next_tick.js:61:11)
TaggedError: failed to say hi
at sayHi3 (repl:3:12)
at demoDatabase.findUser (repl:3:21)
at process.nextTick (repl:8:9)
at process._tickCallback (internal/process/next_tick.js:61:11)
{ userId: 43 }
```
Logging this information (or reporting it to an error monitoring service) hopefully gives you a good start to figuring out what went wrong.
### `async`/`await`
The `OError.tag` approach works with both async/await and callback-oriented code. When using async/await, the pattern is to catch an error, tag it and rethrow:
```js
const promisify = require('util').promisify
demoDatabase.findUserAsync = promisify(demoDatabase.findUser)
async function sayHi4(userId) {
try {
throw new Error('bad')
} catch (err) {
throw new FooError({ info: { foo: 'bar' } }).withCause(err)
const user = await demoDatabase.findUserAsync(userId)
return `Hi ${user.name}`
} catch (error) {
throw OError.tag(error, 'failed to find user', { userId })
}
}
doFoo2()
// =>
// { FooError: failed to foo: bad <-- combined message
// at doFoo2 (repl:5:11) <-- stack trace
// name: 'FooError', <-- correct name
// info: { foo: 'bar' }, <-- attached info
// cause: <-- the cause (inner error)
// Error: bad <-- inner error message
// at doFoo2 (repl:3:11) <-- inner error stack trace
// at repl:1:1
// ...
async function main() {
try {
await sayHi4(43)
} catch (error) {
OError.tag(error, 'failed to say hi')
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
}
main()
```
The resulting full stack trace points to `sayHi4` in `main`, as expected:
```
Error: not found
at process.nextTick (repl:8:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
TaggedError: failed to find user
at sayHi4 (repl:6:18)
at process._tickCallback (internal/process/next_tick.js:68:7)
TaggedError: failed to say hi
at main (repl:5:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
{ userId: 43 }
```
### Better Async Stack Traces in Node 12+
The above output is from node 10. Node 12 has improved stack traces for async code that uses native promises. However, until your whole stack, including all libraries, is using async/await and native promises, you're still likely to get unhelpful stack traces. So, the tagging approach still adds value, even in node 12. (And the `info` from tagging can add value even to a good stack trace, because it can contain clues about the input the caused the error.)
## Create Custom Error Classes
Broadly speaking, there are two kinds of errors: those we try to recover from, and those for which we give up (i.e. a 5xx response in a web application). For the latter kind, we usually just want to log a message and stack trace useful for debugging, which `OError.tag` helps with.
To recover from an error, we usually need to know what kind of error it was and perhaps to check some of its properties. Defining a custom Error subclass is a good way to do this. Callers can check the type of the error either with `instanceof` or using a custom property, such as `code`.
With ES6 classes, creating a custom error subclass is mostly as simple as `extends Error`. One extra line is required to set the error's `name` appropriately, and inheriting from `OError` handles this implementation detail. Here's an example:
```js
class UserNotFoundError extends OError {
constructor() {
super('user not found')
}
}
try {
doFoo2()
} catch (err) {
console.log(OError.getFullStack(err))
throw new UserNotFoundError()
} catch (error) {
console.error(`instanceof Error: ${error instanceof Error}`)
console.error(
`instanceof UserNotFoundError: ${error instanceof UserNotFoundError}`
)
console.error(error.stack)
}
// =>
// FooError: failed to foo: bad
// at doFoo2 (repl:5:11)
// at repl:2:3
// ...
// caused by: Error: bad
// at doFoo2 (repl:3:11)
// at repl:2:3
// ...
```
```
instanceof Error: true
instanceof UserNotFoundError: true
UserNotFoundError: user not found
at repl:2:9
...
```
### Attaching Extra Info
Whether for helping with error recovery or just for debugging, it is often helpful to include some of the state that caused the error in the error. One way to do this is to put it in the message, but this has a few problems:
- Even if the error is later handled and recovered from, we spend time stringifying the state to add it to the error message.
- Error monitoring systems often look at the message when trying to group similar errors together, and they can get confused by the ever-changing messages.
- When using structured logging, you lose the ability to easily query or filter the logs based on the state; instead clever regexes may be required to get it out of the messages.
Instead, `OError`s (and subclasses) support an `info` object that can contain arbitrary data. Using `info`, we might write the above example as:
```js
class UserNotFoundError extends OError {
constructor(userId) {
super('user not found', { userId })
}
}
try {
throw new UserNotFoundError(123)
} catch (error) {
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
```
```
UserNotFoundError: user not found
at repl:2:9
...
{ userId: 123 }
```
The `OError.getFullInfo` helper merges the `info` on custom errors and any info added with `OError.tag` on its way up the stack. It is intended for use when logging errors. If trying to recover from an error that is known to be a `UserNotFoundError`, it is usually better to interrogate `error.info.userId` directly.
### Wrapping an Internal Error
Detecting a condition like 'user not found' in the example above often starts with an internal database error. It is possible to just let the internal database error propagate all the way up through the stack, but this makes the code more coupled to the internals of the database (or database driver). It is often cleaner to handle and wrap the internal error in one that is under your control. Tying up the examples above:
```js
async function sayHi5(userId) {
try {
const user = await demoDatabase.findUserAsync(userId)
return `Hi ${user.name}`
} catch (error) {
if (error.message === 'not found') {
throw new UserNotFoundError(userId).withCause(error)
}
}
}
async function main() {
try {
await sayHi5(43)
} catch (error) {
OError.tag(error, 'failed to say hi')
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
}
main()
```
The output includes the wrapping error, the tag and the cause, together with the info:
```
UserNotFoundError: user not found
at sayHi5 (repl:7:13)
at process._tickCallback (internal/process/next_tick.js:68:7)
TaggedError: failed to say hi
at main (repl:5:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
caused by:
Error: not found
at process.nextTick (repl:8:18)
at process._tickCallback (internal/process/next_tick.js:61:11)
{ userId: 43 }
```
## OError API Reference
<a name="OError"></a>
* [OError](#OError)
* [new OError(message, [info], [cause])](#new_OError_new)
* _instance_
* [.withInfo(info)](#OError+withInfo) ⇒ <code>this</code>
* [.withCause(cause)](#OError+withCause) ⇒ <code>this</code>
* _static_
* [.tag(error, [message], [info])](#OError.tag) ⇒ <code>Error</code>
* [.getFullInfo(error)](#OError.getFullInfo) ⇒ <code>Object</code>
* [.getFullStack(error)](#OError.getFullStack) ⇒ <code>string</code>
<a name="new_OError_new"></a>
### new OError(message, [info], [cause])
| Param | Type | Description |
| --- | --- | --- |
| message | <code>string</code> | as for built-in Error |
| [info] | <code>Object</code> | extra data to attach to the error |
| [cause] | <code>Error</code> | the internal error that caused this error |
<a name="OError+withInfo"></a>
### oError.withInfo(info) ⇒ <code>this</code>
Set the extra info object for this error.
**Kind**: instance method of [<code>OError</code>](#OError)
| Param | Type | Description |
| --- | --- | --- |
| info | <code>Object</code> \| <code>null</code> \| <code>undefined</code> | extra data to attach to the error |
<a name="OError+withCause"></a>
### oError.withCause(cause) ⇒ <code>this</code>
Wrap the given error, which caused this error.
**Kind**: instance method of [<code>OError</code>](#OError)
| Param | Type | Description |
| --- | --- | --- |
| cause | <code>Error</code> | the internal error that caused this error |
<a name="OError.tag"></a>
### OError.tag(error, [message], [info]) ⇒ <code>Error</code>
Tag debugging information onto any error (whether an OError or not) and
return it.
**Kind**: static method of [<code>OError</code>](#OError)
**Returns**: <code>Error</code> - the modified `error` argument
| Param | Type | Description |
| --- | --- | --- |
| error | <code>Error</code> | the error to tag |
| [message] | <code>string</code> | message with which to tag `error` |
| [info] | <code>Object</code> | extra data with wich to tag `error` |
<a name="OError.getFullInfo"></a>
### OError.getFullInfo(error) ⇒ <code>Object</code>
The merged info from any `tag`s on the given error.
If an info property is repeated, the last one wins.
**Kind**: static method of [<code>OError</code>](#OError)
| Param | Type | Description |
| --- | --- | --- |
| error | <code>Error</code> \| <code>null</code> \| <code>undefined</code> | any errror (may or may not be an `OError`) |
<a name="OError.getFullStack"></a>
### OError.getFullStack(error) ⇒ <code>string</code>
Return the `stack` property from `error`, including the `stack`s for any
tagged errors added with `OError.tag` and for any `cause`s.
**Kind**: static method of [<code>OError</code>](#OError)
| Param | Type | Description |
| --- | --- | --- |
| error | <code>Error</code> \| <code>null</code> \| <code>undefined</code> | any error (may or may not be an `OError`) |
<!-- END API REFERENCE -->
## References
- [MDN: Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)

View file

@ -0,0 +1,44 @@
//
// A quick microbenchmark for OError.tag.
//
const OError = require('..')
function benchmark(fn, repeats = 100000) {
const startTime = process.hrtime()
for (let i = 0; i < repeats; ++i) {
fn()
}
const elapsed = process.hrtime(startTime)
return elapsed[0] * 1e3 + elapsed[1] * 1e-6
}
function throwError() {
throw new Error('here is a test error')
}
console.log(
'no tagging: ',
benchmark(() => {
try {
throwError()
return 1
} catch (error) {
return 0
}
}),
'ms'
)
console.log(
'tagging: ',
benchmark(() => {
try {
throwError()
return 1
} catch (error) {
OError.tag(error, 'here is a test tag')
return 0
}
}),
'ms'
)

View file

@ -0,0 +1,141 @@
// This is the code from the README.
const OError = require('..')
const demoDatabase = {
findUser(id, callback) {
process.nextTick(() => {
// return result asynchronously
if (id === 42) {
callback(null, { name: 'Bob' })
} else {
callback(new Error('not found'))
}
})
},
}
function sayHi1(userId, callback) {
demoDatabase.findUser(userId, (err, user) => {
if (err) return callback(err)
callback(null, 'Hi ' + user.name)
})
}
sayHi1(42, (err, result) => {
if (err) {
console.error(err)
} else {
console.log(result)
}
})
sayHi1(43, (err, result) => {
if (err) {
console.error(err)
} else {
console.log(result)
}
})
function sayHi2(userId, callback) {
demoDatabase.findUser(userId, (err, user) => {
if (err) return callback(OError.tag(err))
callback(null, 'Hi ' + user.name)
})
}
sayHi2(43, (err, result) => {
if (err) {
console.error(OError.getFullStack(OError.tag(err)))
} else {
console.log(result)
}
})
function sayHi3(userId, callback) {
demoDatabase.findUser(userId, (err, user) => {
if (err) return callback(OError.tag(err, 'failed to find user', { userId }))
callback(null, 'Hi ' + user.name)
})
}
sayHi3(43, (err, result) => {
if (err) {
OError.tag(err, 'failed to say hi')
console.error(OError.getFullStack(err))
console.error(OError.getFullInfo(err))
} else {
console.log(result)
}
})
const promisify = require('util').promisify
demoDatabase.findUserAsync = promisify(demoDatabase.findUser)
async function sayHi4NoHandling(userId) {
const user = await demoDatabase.findUserAsync(userId)
return `Hi ${user.name}`
}
async function sayHi4(userId) {
try {
const user = await demoDatabase.findUserAsync(userId)
return `Hi ${user.name}`
} catch (error) {
throw OError.tag(error, 'failed to find user', { userId })
}
}
async function main() {
try {
await sayHi4NoHandling(43)
} catch (error) {
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
try {
await sayHi4(43)
} catch (error) {
OError.tag(error, 'failed to say hi')
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
}
main()
class UserNotFoundError extends OError {
constructor(userId) {
super('user not found', { userId })
}
}
try {
throw new UserNotFoundError(123)
} catch (error) {
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
async function sayHi5(userId) {
try {
const user = await demoDatabase.findUserAsync(userId)
return `Hi ${user.name}`
} catch (error) {
if (error.message === 'not found') {
throw new UserNotFoundError(userId).withCause(error)
}
}
}
async function main2() {
try {
await sayHi5(43)
} catch (error) {
OError.tag(error, 'failed to say hi')
console.error(OError.getFullStack(error))
console.error(OError.getFullInfo(error))
}
}
main2()

View file

@ -0,0 +1,49 @@
#!/usr/bin/env node
const fs = require('fs')
const jsdoc2md = require('jsdoc-to-markdown')
const toc = require('markdown-toc')
const README = 'README.md'
const HEADER = '## OError API Reference'
const FOOTER = '<!-- END API REFERENCE -->'
async function main() {
const apiDocs = await jsdoc2md.render({ files: 'index.js' })
const apiDocLines = apiDocs.trim().split(/\r?\n/g)
// The first few lines don't make much sense when included in the README.
const apiDocStart = apiDocLines.indexOf('* [OError](#OError)')
if (apiDocStart === -1) {
console.error('API docs not in expected format for insertion.')
process.exit(1)
}
apiDocLines.splice(1, apiDocStart - 1)
apiDocLines.unshift(HEADER, '')
const readme = await fs.promises.readFile(README, { encoding: 'utf8' })
const readmeLines = readme.split(/\r?\n/g)
const apiStart = readmeLines.indexOf(HEADER)
const apiEnd = readmeLines.indexOf(FOOTER)
if (apiStart === -1 || apiEnd === -1) {
console.error('Could not find the API Reference section.')
process.exit(1)
}
Array.prototype.splice.apply(
readmeLines,
[apiStart, apiEnd - apiStart].concat(apiDocLines)
)
const readmeWithApi = readmeLines.join('\n')
let readmeWithApiAndToc = toc.insert(readmeWithApi)
// Unfortunately, the ⇒ breaks the generated TOC links.
readmeWithApiAndToc = readmeWithApiAndToc.replace(/-%E2%87%92-/g, '--')
await fs.promises.writeFile(README, readmeWithApiAndToc)
}
main()

View file

@ -1,89 +0,0 @@
const OError = require('./index')
class HttpError extends OError {
constructor(options) {
super(options)
this.statusCode = options.statusCode || 500
}
}
class InternalServerError extends HttpError {
constructor(options) {
super({ message: 'Internal Server Error', statusCode: 500, ...options })
}
}
class ServiceUnavailableError extends HttpError {
constructor(options) {
super({ message: 'Service Unavailable', statusCode: 503, ...options })
}
}
class BadRequestError extends HttpError {
constructor(options) {
super({ message: 'Bad Request', statusCode: 400, ...options })
}
}
class UnauthorizedError extends HttpError {
constructor(options) {
super({ message: 'Unauthorized', statusCode: 401, ...options })
}
}
class ForbiddenError extends HttpError {
constructor(options) {
super({ message: 'Forbidden', statusCode: 403, ...options })
}
}
class NotFoundError extends HttpError {
constructor(options) {
super({ message: 'Not Found', statusCode: 404, ...options })
}
}
class MethodNotAllowedError extends HttpError {
constructor(options) {
super({ message: 'Method Not Allowed', statusCode: 405, ...options })
}
}
class NotAcceptableError extends HttpError {
constructor(options) {
super({ message: 'Not Acceptable', statusCode: 406, ...options })
}
}
class ConflictError extends HttpError {
constructor(options) {
super({ message: 'Conflict', statusCode: 409, ...options })
}
}
class UnprocessableEntityError extends HttpError {
constructor(options) {
super({ message: 'Unprocessable Entity', statusCode: 422, ...options })
}
}
class TooManyRequestsError extends HttpError {
constructor(options) {
super({ message: 'Too Many Requests', statusCode: 429, ...options })
}
}
module.exports = {
HttpError,
InternalServerError,
ServiceUnavailableError,
BadRequestError,
UnauthorizedError,
ForbiddenError,
NotFoundError,
MethodNotAllowedError,
NotAcceptableError,
ConflictError,
UnprocessableEntityError,
TooManyRequestsError,
}

58
libraries/o-error/index.d.ts vendored Normal file
View file

@ -0,0 +1,58 @@
export = OError;
/**
* Light-weight helpers for handling JavaScript Errors in node.js and the
* browser.
*/
declare class OError extends Error {
/**
* Tag debugging information onto any error (whether an OError or not) and
* return it.
*
* @param {Error} error the error to tag
* @param {string} [message] message with which to tag `error`
* @param {Object} [info] extra data with wich to tag `error`
* @return {Error} the modified `error` argument
*/
static tag(error: Error, message?: string, info?: any): Error;
/**
* The merged info from any `tag`s on the given error.
*
* If an info property is repeated, the last one wins.
*
* @param {Error | null | undefined} error any errror (may or may not be an `OError`)
* @return {Object}
*/
static getFullInfo(error: Error): any;
/**
* Return the `stack` property from `error`, including the `stack`s for any
* tagged errors added with `OError.tag` and for any `cause`s.
*
* @param {Error | null | undefined} error any error (may or may not be an `OError`)
* @return {string}
*/
static getFullStack(error: Error): string;
/**
* @param {string} message as for built-in Error
* @param {Object} [info] extra data to attach to the error
* @param {Error} [cause] the internal error that caused this error
*/
constructor(message: string, info?: any, cause?: Error);
info: any;
cause: Error;
/** @private @type {Array<TaggedError>} */
private _oErrorTags;
/**
* Set the extra info object for this error.
*
* @param {Object | null | undefined} info extra data to attach to the error
* @return {this}
*/
withInfo(info: any): OError;
/**
* Wrap the given error, which caused this error.
*
* @param {Error} cause the internal error that caused this error
* @return {this}
*/
withCause(cause: Error): OError;
}

View file

@ -1,93 +1,136 @@
'use strict'
/**
* Make custom error types that pass `instanceof` checks, have stack traces,
* support custom messages and properties, and support wrapping errors (causes).
*
* @module
*/
/**
* A base class for custom errors that handles:
*
* 1. Wrapping an optional 'cause'.
* 2. Storing an 'info' object with additional data.
* 3. Setting the name to the subclass name.
*
* @extends Error
* Light-weight helpers for handling JavaScript Errors in node.js and the
* browser.
*/
class OError extends Error {
/**
* @param {string} message as for built-in Error
* @param {?object} info extra data to attach to the error
* @param {Object} [info] extra data to attach to the error
* @param {Error} [cause] the internal error that caused this error
*/
constructor({ message, info }) {
constructor(message, info, cause) {
super(message)
this.name = this.constructor.name
if (info) {
this.info = info
}
if (info) this.info = info
if (cause) this.cause = cause
/** @private @type {Array<TaggedError>} */
this._oErrorTags // eslint-disable-line
}
/**
* Set the extra info object for this error.
*
* @param {Object | null | undefined} info extra data to attach to the error
* @return {this}
*/
withInfo(info) {
this.info = info
return this
}
/**
* Wrap the given error, which caused this error.
*
* @param {Error} cause
* @param {Error} cause the internal error that caused this error
* @return {this}
*/
withCause(cause) {
this.cause = cause
if (this.message && cause.message) {
this.message += ': ' + cause.message
}
return this
}
/**
* Tag debugging information onto any error (whether an OError or not) and
* return it.
*
* @param {Error} error the error to tag
* @param {string} [message] message with which to tag `error`
* @param {Object} [info] extra data with wich to tag `error`
* @return {Error} the modified `error` argument
*/
static tag(error, message, info) {
const oError = /** @type{OError} */ (error)
if (!oError._oErrorTags) oError._oErrorTags = []
let tag
if (Error.captureStackTrace) {
// Hide this function in the stack trace, and avoid capturing it twice.
tag = /** @type TaggedError */ ({ name: 'TaggedError', message, info })
Error.captureStackTrace(tag, OError.tag)
} else {
tag = new TaggedError(message, info)
}
oError._oErrorTags.push(tag)
return error
}
/**
* The merged info from any `tag`s on the given error.
*
* If an info property is repeated, the last one wins.
*
* @param {Error | null | undefined} error any errror (may or may not be an `OError`)
* @return {Object}
*/
static getFullInfo(error) {
const info = {}
if (!error) return info
const oError = /** @type{OError} */ (error)
if (typeof oError.info === 'object') Object.assign(info, oError.info)
if (oError._oErrorTags) {
for (const tag of oError._oErrorTags) {
Object.assign(info, tag.info)
}
}
return info
}
/**
* Return the `stack` property from `error`, including the `stack`s for any
* tagged errors added with `OError.tag` and for any `cause`s.
*
* @param {Error | null | undefined} error any error (may or may not be an `OError`)
* @return {string}
*/
static getFullStack(error) {
if (!error) return ''
const oError = /** @type{OError} */ (error)
let stack = oError.stack
if (Array.isArray(oError._oErrorTags) && oError._oErrorTags.length) {
stack += `\n${oError._oErrorTags.map((tag) => tag.stack).join('\n')}`
}
const causeStack = oError.cause && OError.getFullStack(oError.cause)
if (causeStack) {
stack += '\ncaused by:\n' + indent(causeStack)
}
return stack
}
}
/**
* Return the `info` property from `error` and recursively merge the `info`
* properties from the error's causes, if any.
* Used to record a stack trace every time we tag info onto an Error.
*
* If a property is repeated, the first one in the cause chain wins.
*
* @param {?Error} error assumed not to have circular causes
* @return {Object}
* @private
* @extends OError
*/
function getFullInfo(error) {
if (!error) return {}
const info = getFullInfo(error.cause)
if (typeof error.info === 'object') Object.assign(info, error.info)
return info
}
class TaggedError extends OError {}
/**
* Return the `stack` property from `error` and recursively append the `stack`
* properties from the error's causes, if any.
*
* @param {?Error} error assumed not to have circular causes
* @return {string}
*/
function getFullStack(error) {
if (!error) return ''
const causeStack = getFullStack(error.cause)
if (causeStack) return error.stack + '\ncaused by: ' + causeStack
return error.stack
function indent(string) {
return string.replace(/^/gm, ' ')
}
/**
* Is `error` or one of its causes an instance of `klass`?
*
* @param {?Error} error assumed not to have circular causes
* @param {function} klass
* @return {Boolean}
*/
function hasCauseInstanceOf(error, klass) {
if (!error) return false
return error instanceof klass || hasCauseInstanceOf(error.cause, klass)
}
OError.getFullInfo = getFullInfo
OError.getFullStack = getFullStack
OError.hasCauseInstanceOf = hasCauseInstanceOf
module.exports = OError

File diff suppressed because it is too large Load diff

View file

@ -1,16 +1,23 @@
{
"name": "@overleaf/o-error",
"version": "2.1.0",
"version": "3.0.0",
"description": "Make custom error types that pass `instanceof` checks, have stack traces, support custom messages and properties, and can wrap causes (like VError).",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"lint": "eslint .",
"test": "mocha --require test/support"
"update-readme": "doc/update-readme.js",
"test": "mocha",
"typecheck": "tsc --allowJs --checkJs --noEmit --moduleResolution node --target ES6 *.js test/**/*.js",
"declaration:build": "rm -f index.d.ts && tsc --allowJs --declaration --emitDeclarationOnly --moduleResolution node --target ES6 index.js",
"declaration:check": "git diff --exit-code -- index.d.ts",
"prepublishOnly": "npm run --silent declaration:build && npm run --silent declaration:check"
},
"author": "Overleaf (https://www.overleaf.com)",
"license": "MIT",
"repository": "github:overleaf/o-error",
"devDependencies": {
"@types/node": "^13.13.2",
"chai": "^3.3.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
@ -23,7 +30,10 @@
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"jsdoc-to-markdown": "^5.0.3",
"markdown-toc": "^1.2.0",
"mocha": "^7.1.1",
"prettier": "^2.0.2"
"prettier": "^2.0.2",
"typescript": "^3.8.3"
}
}

View file

@ -1,20 +0,0 @@
const OError = require('..')
const HttpErrors = require('../http')
describe('OError/http', function () {
it('is instance of OError', function () {
try {
throw new HttpErrors.ConflictError()
} catch (e) {
expect(e).to.be.instanceof(OError)
}
})
it('has status code', function () {
try {
throw new HttpErrors.ConflictError()
} catch (e) {
expect(e.statusCode).to.equal(409)
}
})
})

View file

@ -1,52 +1,201 @@
const { getFullInfo, getFullStack, hasCauseInstanceOf } = require('..')
const { expect } = require('chai')
const { promisify } = require('util')
const OError = require('..')
const {
expectError,
expectFullStackWithoutStackFramesToEqual,
} = require('./support')
describe('OError.tag', function () {
it('tags errors thrown from an async function', async function () {
const delay = promisify(setTimeout)
async function foo() {
await delay(10)
throw new Error('foo error')
}
async function bar() {
try {
await foo()
} catch (error) {
throw OError.tag(error, 'failed to bar', { bar: 'baz' })
}
}
async function baz() {
try {
await bar()
} catch (error) {
throw OError.tag(error, 'failed to baz', { baz: 'bat' })
}
}
try {
await baz()
expect.fail('should have thrown')
} catch (error) {
expectError(error, {
name: 'Error',
klass: Error,
message: 'Error: foo error',
firstFrameRx: /at foo/,
})
expectFullStackWithoutStackFramesToEqual(error, [
'Error: foo error',
'TaggedError: failed to bar',
'TaggedError: failed to baz',
])
expect(OError.getFullInfo(error)).to.eql({
bar: 'baz',
baz: 'bat',
})
}
})
it('tags errors thrown from a promise rejection', async function () {
function foo() {
return new Promise((resolve, reject) => {
setTimeout(function () {
reject(new Error('foo error'))
}, 10)
})
}
async function bar() {
try {
await foo()
} catch (error) {
throw OError.tag(error, 'failed to bar', { bar: 'baz' })
}
}
async function baz() {
try {
await bar()
} catch (error) {
throw OError.tag(error, 'failed to baz', { baz: 'bat' })
}
}
try {
await baz()
expect.fail('should have thrown')
} catch (error) {
expectError(error, {
name: 'Error',
klass: Error,
message: 'Error: foo error',
firstFrameRx: /_onTimeout/,
})
expectFullStackWithoutStackFramesToEqual(error, [
'Error: foo error',
'TaggedError: failed to bar',
'TaggedError: failed to baz',
])
expect(OError.getFullInfo(error)).to.eql({
bar: 'baz',
baz: 'bat',
})
}
})
it('tags errors yielded through callbacks', function (done) {
function foo(cb) {
setTimeout(function () {
cb(new Error('foo error'))
}, 10)
}
function bar(cb) {
foo(function (err) {
if (err) {
return cb(OError.tag(err, 'failed to bar', { bar: 'baz' }))
}
cb()
})
}
function baz(cb) {
bar(function (err) {
if (err) {
return cb(OError.tag(err, 'failed to baz', { baz: 'bat' }))
}
cb()
})
}
baz(function (err) {
if (err) {
expectError(err, {
name: 'Error',
klass: Error,
message: 'Error: foo error',
firstFrameRx: /_onTimeout/,
})
expectFullStackWithoutStackFramesToEqual(err, [
'Error: foo error',
'TaggedError: failed to bar',
'TaggedError: failed to baz',
])
expect(OError.getFullInfo(err)).to.eql({
bar: 'baz',
baz: 'bat',
})
return done()
}
expect.fail('should have yielded an error')
})
})
})
describe('OError.getFullInfo', function () {
it('works on a normal error', function () {
const err = new Error('foo')
expect(getFullInfo(err)).to.deep.equal({})
expect(OError.getFullInfo(err)).to.deep.equal({})
})
it('works on an error with .info', function () {
const err = new Error('foo')
err.info = { userId: 123 }
expect(getFullInfo(err)).to.deep.equal({ userId: 123 })
it('works on an error with tags', function () {
const err = OError.tag(new Error('foo'), 'bar', { userId: 123 })
expect(OError.getFullInfo(err)).to.deep.equal({ userId: 123 })
})
it('merges info from a cause chain', function () {
it('merges info from an error and its tags', function () {
const err = new OError('foo').withInfo({ projectId: 456 })
OError.tag(err, 'failed to foo', { userId: 123 })
expect(OError.getFullInfo(err)).to.deep.equal({
projectId: 456,
userId: 123,
})
})
it('does not merge info from a cause', function () {
const err1 = new Error('foo')
const err2 = new Error('bar')
err1.cause = err2
err2.info = { userId: 123 }
expect(getFullInfo(err1)).to.deep.equal({ userId: 123 })
expect(OError.getFullInfo(err1)).to.deep.equal({})
})
it('merges info from a cause chain with no info', function () {
const err1 = new Error('foo')
const err2 = new Error('bar')
err1.cause = err2
expect(getFullInfo(err1)).to.deep.equal({})
})
it('merges info from a cause chain with duplicate keys', function () {
const err1 = new Error('foo')
const err2 = new Error('bar')
err1.cause = err2
err1.info = { userId: 123 }
err2.info = { userId: 456 }
expect(getFullInfo(err1)).to.deep.equal({ userId: 123 })
it('merges info from tags with duplicate keys', function () {
const err1 = OError.tag(new Error('foo'), 'bar', { userId: 123 })
const err2 = OError.tag(err1, 'bat', { userId: 456 })
expect(OError.getFullInfo(err2)).to.deep.equal({ userId: 456 })
})
it('works on an error with .info set to a string', function () {
const err = new Error('foo')
err.info = 'test'
expect(getFullInfo(err)).to.deep.equal({})
expect(OError.getFullInfo(err)).to.deep.equal({})
})
})
describe('OError.getFullStack', function () {
it('works on a normal error', function () {
const err = new Error('foo')
const fullStack = getFullStack(err)
const fullStack = OError.getFullStack(err)
expect(fullStack).to.match(/^Error: foo$/m)
expect(fullStack).to.match(/^\s+at /m)
})
@ -56,28 +205,62 @@ describe('OError.getFullStack', function () {
const err2 = new Error('bar')
err1.cause = err2
const fullStack = getFullStack(err1)
const fullStack = OError.getFullStack(err1)
expect(fullStack).to.match(/^Error: foo$/m)
expect(fullStack).to.match(/^\s+at /m)
expect(fullStack).to.match(/^caused by: Error: bar$/m)
})
})
describe('OError.hasCauseInstanceOf', function () {
it('works on a normal error', function () {
const err = new Error('foo')
expect(hasCauseInstanceOf(null, Error)).to.be.false
expect(hasCauseInstanceOf(err, Error)).to.be.true
expect(hasCauseInstanceOf(err, RangeError)).to.be.false
})
it('works on an error with a cause', function () {
const err1 = new Error('foo')
const err2 = new RangeError('bar')
err1.cause = err2
expect(hasCauseInstanceOf(err1, Error)).to.be.true
expect(hasCauseInstanceOf(err1, RangeError)).to.be.true
expect(hasCauseInstanceOf(err1, TypeError)).to.be.false
expect(fullStack).to.match(/^caused by:\n\s+Error: bar$/m)
})
it('works on both tags and causes', async function () {
// Here's the actual error.
function tryToFoo() {
try {
throw Error('foo')
} catch (error) {
throw OError.tag(error, 'failed to foo', { foo: 1 })
}
}
// Inside another function that wraps it.
function tryToBar() {
try {
tryToFoo()
} catch (error) {
throw new OError('failed to bar').withCause(error)
}
}
// And it is in another try.
try {
try {
tryToBar()
expect.fail('should have thrown')
} catch (error) {
throw OError.tag(error, 'failed to bat', { bat: 1 })
}
} catch (error) {
// We catch the wrapping error.
expectError(error, {
name: 'OError',
klass: OError,
message: 'OError: failed to bar',
firstFrameRx: /tryToBar/,
})
// But the stack contains all of the errors and tags.
expectFullStackWithoutStackFramesToEqual(error, [
'OError: failed to bar',
'TaggedError: failed to bat',
'caused by:',
' Error: foo',
' TaggedError: failed to foo',
])
// The info from the wrapped cause should not leak out.
expect(OError.getFullInfo(error)).to.eql({ bat: 1 })
// But it should still be recorded.
expect(OError.getFullInfo(error.cause)).to.eql({ foo: 1 })
}
})
})

View file

@ -1,19 +1,40 @@
const { expect } = require('chai')
const OError = require('..')
const { expectError } = require('./support')
const {
expectError,
expectFullStackWithoutStackFramesToEqual,
} = require('./support')
class CustomError1 extends OError {
constructor(options) {
super({ message: 'failed to foo', ...options })
constructor() {
super('failed to foo')
}
}
class CustomError2 extends OError {
constructor(options) {
super({ message: 'failed to bar', ...options })
constructor(customMessage) {
super(customMessage || 'failed to bar')
}
}
describe('OError', function () {
it('can have an info object', function () {
const err1 = new OError('foo', { foo: 1 })
expect(err1.info).to.eql({ foo: 1 })
const err2 = new OError('foo').withInfo({ foo: 2 })
expect(err2.info).to.eql({ foo: 2 })
})
it('can have a cause', function () {
const err1 = new OError('foo', { foo: 1 }, new Error('cause 1'))
expect(err1.cause.message).to.equal('cause 1')
const err2 = new OError('foo').withCause(new Error('cause 2'))
expect(err2.cause.message).to.equal('cause 2')
})
it('handles a custom error type with a cause', function () {
function doSomethingBadInternally() {
throw new Error('internal error')
@ -22,27 +43,27 @@ describe('OError', function () {
function doSomethingBad() {
try {
doSomethingBadInternally()
} catch (err) {
throw new CustomError1({ info: { userId: 123 } }).withCause(err)
} catch (error) {
throw new CustomError1().withCause(error)
}
}
try {
doSomethingBad()
expect.fail('should have thrown')
} catch (e) {
expectError(e, {
} catch (error) {
expectError(error, {
name: 'CustomError1',
klass: CustomError1,
message: 'CustomError1: failed to foo: internal error',
message: 'CustomError1: failed to foo',
firstFrameRx: /doSomethingBad/,
})
expect(OError.getFullInfo(e)).to.deep.equal({ userId: 123 })
const fullStack = OError.getFullStack(e)
expect(fullStack).to.match(
/^CustomError1: failed to foo: internal error$/m
)
expect(fullStack).to.match(/^caused by: Error: internal error$/m)
expect(OError.getFullInfo(error)).to.deep.equal({})
expectFullStackWithoutStackFramesToEqual(error, [
'CustomError1: failed to foo',
'caused by:',
' Error: internal error',
])
}
})
@ -54,51 +75,37 @@ describe('OError', function () {
function doBar() {
try {
doSomethingBadInternally()
} catch (err) {
throw new CustomError2({ info: { database: 'a' } }).withCause(err)
} catch (error) {
throw new CustomError2('failed to bar!').withCause(error)
}
}
function doFoo() {
try {
doBar()
} catch (err) {
throw new CustomError1({ info: { userId: 123 } }).withCause(err)
} catch (error) {
throw new CustomError1().withCause(error)
}
}
try {
doFoo()
expect.fail('should have thrown')
} catch (e) {
expectError(e, {
} catch (error) {
expectError(error, {
name: 'CustomError1',
klass: CustomError1,
message: 'CustomError1: failed to foo: failed to bar: internal error',
message: 'CustomError1: failed to foo',
firstFrameRx: /doFoo/,
})
expect(OError.getFullInfo(e)).to.deep.equal({
userId: 123,
database: 'a',
})
const fullStack = OError.getFullStack(e)
expect(fullStack).to.match(
/^CustomError1: failed to foo: failed to bar: internal error$/m
)
expect(fullStack).to.match(
/^caused by: CustomError2: failed to bar: internal error$/m
)
expect(fullStack).to.match(/^caused by: Error: internal error$/m)
}
})
it('handles a custom error without info', function () {
try {
throw new CustomError1({})
} catch (e) {
expect(OError.getFullInfo(e)).to.deep.equal({})
const infoKey = Object.keys(e).find((k) => k === 'info')
expect(infoKey).to.not.exist
expectFullStackWithoutStackFramesToEqual(error, [
'CustomError1: failed to foo',
'caused by:',
' CustomError2: failed to bar!',
' caused by:',
' Error: internal error',
])
expect(OError.getFullInfo(error)).to.deep.equal({})
}
})
})

View file

@ -1,31 +1,53 @@
'use strict'
const { expect } = require('chai')
var chai = require('chai')
global.expect = chai.expect
const OError = require('../..')
exports.expectError = function OErrorExpectError(e, expected) {
// should set the name to the error's name
expect(e.name).to.equal(expected.name)
expect(
e.name,
"error should set the name property to the error's name"
).to.equal(expected.name)
// should be an instance of the error type
expect(e instanceof expected.klass).to.be.true
expect(
e instanceof expected.klass,
'error should be an instance of the error type'
).to.be.true
// should be an instance of the built-in Error type
expect(e instanceof Error).to.be.true
expect(
e instanceof Error,
'error should be an instance of the built-in Error type'
).to.be.true
// should be recognised by util.isError
expect(require('util').types.isNativeError(e)).to.be.true
expect(
require('util').types.isNativeError(e),
'error should be recognised by util.types.isNativeError'
).to.be.true
// should have a stack trace
expect(e.stack).to.be.truthy
expect(e.stack, 'error should have a stack trace').to.be.truthy
// toString should return the default error message formatting
expect(e.toString()).to.equal(expected.message)
expect(
e.toString(),
'toString should return the default error message formatting'
).to.equal(expected.message)
// stack should start with the default error message formatting
expect(e.stack.split('\n')[0]).to.match(new RegExp(`^${expected.name}:`))
expect(
e.stack.split('\n')[0],
'stack should start with the default error message formatting'
).to.match(new RegExp(`^${expected.name}:`))
// first stack frame should be the function where the error was thrown
expect(e.stack.split('\n')[1]).to.match(expected.firstFrameRx)
expect(
e.stack.split('\n')[1],
'first stack frame should be the function where the error was thrown'
).to.match(expected.firstFrameRx)
}
exports.expectFullStackWithoutStackFramesToEqual = function (error, expected) {
const fullStack = OError.getFullStack(error)
const fullStackWithoutFrames = fullStack
.split('\n')
.filter((line) => !/^\s+at\s/.test(line))
expect(
fullStackWithoutFrames,
'full stack without frames should equal'
).to.deep.equal(expected)
}