From fe02f3545e356c8b6e73b2f5d54739b52ebc6ea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20FIDRY?= Date: Tue, 6 Dec 2022 17:41:10 +0100 Subject: [PATCH] Extract HttpModule error extraction into a dedicated function --- packages/angular/src/errorhandler.ts | 38 +++++++++++++++------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/packages/angular/src/errorhandler.ts b/packages/angular/src/errorhandler.ts index 9c091f2a2b16..2d306b01aa30 100644 --- a/packages/angular/src/errorhandler.ts +++ b/packages/angular/src/errorhandler.ts @@ -21,6 +21,26 @@ export interface ErrorHandlerOptions { extractor?(error: unknown, defaultExtractor: (error: unknown) => unknown): unknown; } +function extractHttpModuleError(error: HttpErrorResponse): string | Error { + // The `error` property of http exception can be either an `Error` object, which we can use directly... + if (error.error instanceof Error) { + return error.error; + } + + // ... or an`ErrorEvent`, which can provide us with the message but no stack... + if (error.error instanceof ErrorEvent && error.error.message) { + return error.error.message; + } + + // ...or the request body itself, which we can use as a message instead. + if (typeof error.error === 'string') { + return `Server returned code ${error.status} with body "${error.error}"`; + } + + // If we don't have any detailed information, fallback to the request message itself. + return error.message; +} + /** * Implementation of Angular's ErrorHandler provider that can be used as a drop-in replacement for the stock one. */ @@ -101,23 +121,7 @@ class SentryErrorHandler implements AngularErrorHandler { // If it's http module error, extract as much information from it as we can. if (error instanceof HttpErrorResponse) { - // The `error` property of http exception can be either an `Error` object, which we can use directly... - if (error.error instanceof Error) { - return error.error; - } - - // ... or an`ErrorEvent`, which can provide us with the message but no stack... - if (error.error instanceof ErrorEvent && error.error.message) { - return error.error.message; - } - - // ...or the request body itself, which we can use as a message instead. - if (typeof error.error === 'string') { - return `Server returned code ${error.status} with body "${error.error}"`; - } - - // If we don't have any detailed information, fallback to the request message itself. - return error.message; + return extractHttpModuleError(error); } // Nothing was extracted, fallback to default error message.