Skip to content

Commit

Permalink
feat: add Exception.toJSON() method (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
alessiofrittoli authored Jan 3, 2025
1 parent c95160a commit 70164eb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
28 changes: 28 additions & 0 deletions __tests__/exception.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ErrorCode } from '@/code'
import { Exception } from '@/index'

describe( 'Exception', () => {
Expand Down Expand Up @@ -61,4 +62,31 @@ describe( 'Exception.isException()', () => {
.toBe( true )
} )

} )


describe( 'Exception.toJSON()', () => {

it( 'returns a JSON representation of the Exception Class', () => {
const exception = (
new Exception(
'Error message', {
code : ErrorCode.ABORT,
status : 400,
name : 'AbortError',
cause : 'User aborted the request.',
}
)
)

const parsedException = JSON.parse( JSON.stringify( exception ) ) as Exception

expect( Exception.isException( parsedException ) ).toBe( true )
expect( parsedException.message ).toBe( exception.message )
expect( parsedException.code ).toBe( exception.code )
expect( parsedException.name ).toBe( exception.name )
expect( parsedException.cause ).toBe( exception.cause )

} )

} )
17 changes: 16 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ErrorCode } from './code'
import { ErrorCode } from './code'

/**
* Interface representing the options for an Exception.
Expand Down Expand Up @@ -72,4 +72,19 @@ export class Exception<TMessage = string, TCode = ErrorCode> extends Error imple
( typeof error === 'object' && 'typename' in error && error.typename === 'Exception' )
)
}


/**
* Converts the instance to a JSON object.
*
* @returns A JSON representation of the instance, including the message property.
*/
toJSON()
{
return {
...this,
message: this.message,
cause: this.cause,
}
}
}

0 comments on commit 70164eb

Please sign in to comment.