83 lines
2.0 KiB
TypeScript
83 lines
2.0 KiB
TypeScript
import { HttpErrorResponse } from '@angular/common/http';
|
|
import { Injectable, signal } from '@angular/core';
|
|
|
|
export interface ErrorState {
|
|
statusCode: number;
|
|
title: string;
|
|
message: string;
|
|
referenceId?: string;
|
|
errorDetails?: string;
|
|
}
|
|
|
|
export interface ErrorOptions {
|
|
title?: string;
|
|
message?: string;
|
|
referenceId?: string;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class ErrorService {
|
|
private readonly errorSignal = signal<ErrorState | null>(null);
|
|
|
|
readonly error = this.errorSignal.asReadonly();
|
|
|
|
report(error: unknown, options: ErrorOptions = {}): ErrorState {
|
|
const state: ErrorState = {
|
|
statusCode: this.getStatusCode(error),
|
|
title: options.title ?? 'Da ist was schiefgelaufen',
|
|
message:
|
|
options.message ??
|
|
'Ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.',
|
|
referenceId: options.referenceId,
|
|
errorDetails: this.getDebugDetails(error) || undefined,
|
|
};
|
|
|
|
this.errorSignal.set(state);
|
|
return state;
|
|
}
|
|
|
|
consumeError(): ErrorState | null {
|
|
const error = this.errorSignal();
|
|
this.errorSignal.set(null);
|
|
return error;
|
|
}
|
|
|
|
clearError(): void {
|
|
this.errorSignal.set(null);
|
|
}
|
|
|
|
private getStatusCode(error: unknown): number {
|
|
if (error instanceof HttpErrorResponse) {
|
|
return error.status >= 400 && error.status <= 599 ? error.status : 500;
|
|
}
|
|
|
|
return 500;
|
|
}
|
|
|
|
private getDebugDetails(error: unknown): string {
|
|
if (error instanceof HttpErrorResponse) {
|
|
const apiDetail =
|
|
typeof error.error === 'object' &&
|
|
error.error !== null &&
|
|
'detail' in error.error &&
|
|
typeof error.error.detail === 'string'
|
|
? error.error.detail
|
|
: undefined;
|
|
|
|
return apiDetail ?? error.message;
|
|
}
|
|
|
|
if (error instanceof Error) {
|
|
return error.stack ?? error.message;
|
|
}
|
|
|
|
try {
|
|
return JSON.stringify(error, null, 2);
|
|
} catch {
|
|
return String(error);
|
|
}
|
|
}
|
|
}
|