Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DO NOT MERGE YET | NOJIRA - POC for tracking external links, server and client errors and unhandled errors #259

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/golden-sample-app/src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@
aria-live="polite"
></div>

<a href="http://www.google.nl">Google</a>

<!-- Main Content Area -->
<div class="bb-layout__main-content-area">
<router-outlet></router-outlet>
Expand Down
49 changes: 47 additions & 2 deletions apps/golden-sample-app/src/app/app.error-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable, NgZone } from '@angular/core';
import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import {
Tracker,
TrackerEvent,
TrackerEventBase,
TrackerEventPayload,
} from '@backbase/foundation-ang/observability';

function extractRejectionError(error: unknown): Error | unknown {
if (error && typeof error === 'object' && 'rejection' in error) {
Expand All @@ -10,14 +16,35 @@ function extractRejectionError(error: unknown): Error | unknown {
return error;
}

type Optional<Type, Key extends keyof Type> = Omit<Type, Key> &
Partial<Pick<Type, Key>>;

export interface UnhandledErrorTrackerEventPayload extends TrackerEventPayload {
message: string;
stack: string;
}

export class UnhandledErrorTrackerEvent<
T extends Optional<TrackerEventBase, 'name'> = {
payload: UnhandledErrorTrackerEventPayload;
}
> extends TrackerEvent<T['name'] & string, NonNullable<T['payload']>> {
readonly name = 'unhandled-error';
constructor(payload: NonNullable<T['payload']>, journey?: string) {
super(payload, journey);
}
}

@Injectable()
export class AppErrorHandler implements ErrorHandler {
constructor(
private readonly router: Router,
private readonly ngZone: NgZone
private readonly ngZone: NgZone,
private injector: Injector
) {}

handleError(error: Error | unknown): void {
const tracker = this.injector.get(Tracker);
const extractedError = extractRejectionError(error);

if (extractedError instanceof HttpErrorResponse) {
Expand All @@ -33,6 +60,24 @@ export class AppErrorHandler implements ErrorHandler {
return;
}

if (error instanceof Error) {
// Publish the error using your Tracker service
tracker?.publish(
new UnhandledErrorTrackerEvent({
message: error?.message,
stack: error?.stack || 'Unknown error stack',
})
);
} else {
// Publish the error using your Tracker service
tracker?.publish(
new UnhandledErrorTrackerEvent({
message: 'Unknown error message',
stack: 'Unknown error stack',
})
);
}

console.error(error);
}
}
5 changes: 4 additions & 1 deletion apps/golden-sample-app/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,11 @@ import { ActivityMonitorModule } from './auth/activity-monitor';
import packageInfo from 'package-json';
import { ThemeSwitcherModule } from './theme-switcher/theme-switcher.component.module';
import { ThemeManagerService } from './theme-switcher/theme-service';
import { GlobalLinkHandlerDirective } from './directives/global-link-handler.directive';
import { HttpErrorInterceptor } from './interceptors/http-error.interceptor';

@NgModule({
declarations: [AppComponent],
declarations: [AppComponent, GlobalLinkHandlerDirective],
imports: [
BrowserModule,
AppRoutingModule,
Expand Down Expand Up @@ -174,6 +176,7 @@ import { ThemeManagerService } from './theme-switcher/theme-service';
useClass: AppErrorHandler,
},
ThemeManagerService,
{ provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true },
],
bootstrap: [AppComponent],
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import {
Directive,
ElementRef,
HostListener,
Renderer2,
OnInit,
} from '@angular/core';
import { Router } from '@angular/router';
import {
Tracker,
UserActionTrackerEvent,
} from '@backbase/foundation-ang/observability';

class ExternalLinkTrackerEvent extends UserActionTrackerEvent<{
payload: { currentUrl: string; externalUrl: string; xpath: string };
}> {
name = 'external-link-detected';
}

@Directive({
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'a[href]', // This will target all anchor tags with href attribute
})
export class GlobalLinkHandlerDirective implements OnInit {
constructor(
private el: ElementRef,
private renderer: Renderer2,
private router: Router,
private tracker: Tracker
) {}

ngOnInit() {
// Add target="_blank" to all external links
const href = this.el.nativeElement.href;
if (this.isExternalUrl(href)) {
this.renderer.setAttribute(this.el.nativeElement, 'target', '_blank');
this.renderer.setAttribute(
this.el.nativeElement,
'rel',
'noopener noreferrer'
);
}
}

getXPath(element: Element): string {
if (!element) {
return '';
}

if (element.id !== '') {
return `//*[@id="${element.id}"]`;
}

if (element === document.body) {
return '/html/body';
}

let path = '';
let current: Element | null = element;
while (current && current.nodeType === Node.ELEMENT_NODE) {
let index = 0;
let hasFollowingSiblings = false;
for (
let sibling = current.previousSibling;
sibling;
sibling = sibling.previousSibling
) {
if (
sibling.nodeType === Node.ELEMENT_NODE &&
sibling.nodeName === current.nodeName
) {
index++;
}
}

for (
let sibling = current.nextSibling;
sibling && !hasFollowingSiblings;
sibling = sibling.nextSibling
) {
if (sibling.nodeName === current.nodeName) {
hasFollowingSiblings = true;
}
}

const tagName = current.nodeName.toLowerCase();
const pathIndex = index || hasFollowingSiblings ? `[${index + 1}]` : '';
path = `/${tagName}${pathIndex}${path}`;

current = current.parentNode as Element;
}

return path.toLowerCase();
}

@HostListener('click', ['$event'])
onClick(event: Event) {
const href = this.el.nativeElement.href;
const xpath = this.getXPath(this.el.nativeElement);

if (this.isExternalUrl(href)) {
event.preventDefault();

// Track external link event before opening external url.
this.tracker?.publish(
new ExternalLinkTrackerEvent({
currentUrl: this.router.url,
externalUrl: href,
xpath: xpath,
})
);

// Open external links in a new tab/window
window.open(href, '_blank', 'noopener,noreferrer');
} else {
// For internal links, prevent default and use Angular router
event.preventDefault();
this.router.navigateByUrl(href.replace(window.location.origin, ''));
}
}

private isExternalUrl(url: string): boolean {
// Check if the URL is absolute and not part of your app
return (
/^(http|https):\/\//.test(url) && !url.startsWith(window.location.origin)
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {
Tracker,
TrackerEvent,
TrackerEventPayload,
} from '@backbase/foundation-ang/observability';

interface ClientErrorTrackerEventPayload extends TrackerEventPayload {
status: number;
statusText: string;
}

interface ServerErrorTrackerEventPayload extends TrackerEventPayload {
status: number;
statusText: string;
}

class ClientErrorTrackerEvent extends TrackerEvent<
'client-error',
ClientErrorTrackerEventPayload
> {
readonly name = 'client-error';
}
class ServerErrorTrackerEvent extends TrackerEvent<
'server-error',
ServerErrorTrackerEventPayload
> {
readonly name = 'server-error';
}

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private tracker: Tracker) {}

intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status >= 400 && error.status < 600) {
// Handle client errors (4xx) and server errors (5xx)
console.error('HTTP Error Intercepted:', error);

if (error.status >= 500) {
console.error('Server error occurred:', error.message);

switch (error.status) {
case 500:
default:
this.tracker?.publish(
new ServerErrorTrackerEvent({
status: error.status,
statusText: error.statusText,
})
);
}
} else if (error.status >= 400) {
console.error('Client error occurred:', error.message);
switch (error.status) {
case 400:
default:
this.tracker?.publish(
new ClientErrorTrackerEvent({
status: error.status,
statusText: error.statusText,
})
);
}
}
}

// Rethrow the error so it can be handled by the component if needed
return throwError(() => error);
})
);
}
}
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading