Skip to content

Commit

Permalink
Have sanitisedError always return an Error instance (#199)
Browse files Browse the repository at this point in the history
… for the same reasons as explained in ministryofjustice/hmpps-template-typescript#197
  • Loading branch information
ushkarev committed Jun 12, 2023
1 parent 7fa93a3 commit 8fa721a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
14 changes: 8 additions & 6 deletions server/sanitisedError.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,21 @@ describe('sanitised error', () => {
expect(sanitisedError(error)).toEqual(e)
})

it('it should return the error message ', () => {
it('it should return the error message', () => {
const error = {
message: 'error description',
} as unknown as UnsanitisedError
expect(sanitisedError(error)).toEqual({
message: 'error description',
})

expect(sanitisedError(error)).toBeInstanceOf(Error)
expect(sanitisedError(error)).toHaveProperty('message', 'error description')
})

it('it should return an empty object for an unknown error structure', () => {
it('it should return an empty Error instance for an unknown error structure', () => {
const error = {
property: 'unknown',
} as unknown as UnsanitisedError
expect(sanitisedError(error)).toEqual({})

expect(sanitisedError(error)).toBeInstanceOf(Error)
expect(sanitisedError(error)).not.toHaveProperty('property')
})
})
14 changes: 5 additions & 9 deletions server/sanitisedError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ResponseError } from 'superagent'

export interface SanitisedError {
export interface SanitisedError extends Error {
text?: string
status?: number
headers?: unknown
Expand All @@ -12,18 +12,14 @@ export interface SanitisedError {
export type UnsanitisedError = ResponseError

export default function sanitise(error: UnsanitisedError): SanitisedError {
const e = new Error() as SanitisedError
e.message = error.message
e.stack = error.stack
if (error.response) {
const e = new Error(error.message) as SanitisedError
e.text = error.response.text
e.status = error.response.status
e.headers = error.response.headers
e.data = error.response.body
e.message = error.message
e.stack = error.stack
return e
}
return {
message: error.message,
stack: error.stack,
}
return e
}

0 comments on commit 8fa721a

Please sign in to comment.