overleaf/libraries/o-error/test/o-error.test.js

105 lines
2.7 KiB
JavaScript
Raw Normal View History

2019-07-05 12:55:53 -04:00
const OError = require('..')
const { expectError } = require('./support')
2019-07-05 12:55:53 -04:00
class CustomError1 extends OError {
constructor(info) {
super('failed to foo', info)
}
}
2019-07-05 12:55:53 -04:00
class CustomError2 extends OError {
constructor(customMessage, info) {
super(customMessage || 'failed to bar', info)
}
}
2020-04-17 03:44:50 -04:00
describe('OError', function () {
it('handles a custom error type with a cause', function () {
function doSomethingBadInternally() {
throw new Error('internal error')
}
2020-04-17 03:44:50 -04:00
function doSomethingBad() {
try {
doSomethingBadInternally()
} catch (err) {
throw new CustomError1({ userId: 123 }).withCause(err)
}
}
try {
doSomethingBad()
expect.fail('should have thrown')
} catch (e) {
expectError(e, {
name: 'CustomError1',
klass: CustomError1,
message: 'CustomError1: failed to foo: internal error',
2020-04-17 03:44:50 -04:00
firstFrameRx: /doSomethingBad/,
})
2019-07-05 12:55:53 -04:00
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
)
2020-04-17 03:44:50 -04:00
expect(fullStack).to.match(/^caused by: Error: internal error$/m)
}
})
2020-04-17 03:44:50 -04:00
it('handles a custom error type with nested causes', function () {
function doSomethingBadInternally() {
throw new Error('internal error')
}
2020-04-17 03:44:50 -04:00
function doBar() {
try {
doSomethingBadInternally()
} catch (err) {
throw new CustomError2('failed to bar!', { inner: 'a' }).withCause(err)
}
}
2020-04-17 03:44:50 -04:00
function doFoo() {
try {
doBar()
} catch (err) {
throw new CustomError1({ userId: 123 }).withCause(err)
}
}
try {
doFoo()
expect.fail('should have thrown')
} catch (e) {
expectError(e, {
name: 'CustomError1',
klass: CustomError1,
message: 'CustomError1: failed to foo: failed to bar!: internal error',
2020-04-17 03:44:50 -04:00
firstFrameRx: /doFoo/,
})
2019-07-05 12:55:53 -04:00
expect(OError.getFullInfo(e)).to.deep.equal({
userId: 123,
inner: 'a',
})
2019-07-05 12:55:53 -04:00
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
)
2020-04-17 03:44:50 -04:00
expect(fullStack).to.match(/^caused by: Error: internal error$/m)
}
})
2020-04-17 03:44:50 -04:00
it('handles a custom error without info', function () {
try {
throw new CustomError1()
} catch (e) {
2019-07-05 12:55:53 -04:00
expect(OError.getFullInfo(e)).to.deep.equal({})
2020-04-17 05:59:27 -04:00
const infoKey = Object.keys(e).find((k) => k === 'info')
expect(infoKey).to.not.exist
}
})
})