From 278fdf116648debf6da67907eb78c96c3dea5880 Mon Sep 17 00:00:00 2001 From: Harminder Virk Date: Wed, 9 Oct 2024 10:10:42 +0530 Subject: [PATCH] feat: add support for self rendering custom exceptions --- src/exception_handler.ts | 7 +++++++ tests/exception_handler.spec.ts | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/exception_handler.ts b/src/exception_handler.ts index 3589cf3..db4353c 100644 --- a/src/exception_handler.ts +++ b/src/exception_handler.ts @@ -97,6 +97,13 @@ export class ExceptionHandler { return } + /** + * Allow errors to be self handled. + */ + if ('render' in error && typeof error.render === 'function') { + return error.render(error, kernel) + } + /** * Log error message only when not in debug mode */ diff --git a/tests/exception_handler.spec.ts b/tests/exception_handler.spec.ts index 980467d..588a909 100644 --- a/tests/exception_handler.spec.ts +++ b/tests/exception_handler.spec.ts @@ -122,4 +122,22 @@ test.group('Exception handler', () => { assert.equal(logs[0].stream, 'stderr') assert.equal(logs[0].message, 'bgRed(white( ERROR )) Something went wrong') }) + + test('allow errors to be self handled', async ({ assert }) => { + const kernel = Kernel.create() + kernel.ui.switchMode('raw') + + class CustomError extends Exception { + render(error: CustomError, $kernel: Kernel) { + $kernel.ui.logger.logError(`custom: ${error.message}`) + } + } + + await new ExceptionHandler().render(new CustomError('Something went wrong'), kernel) + + const logs = kernel.ui.logger.getLogs() + assert.lengthOf(logs, 1) + assert.equal(logs[0].stream, 'stderr') + assert.equal(logs[0].message, 'custom: Something went wrong') + }) })