fix: adjust handling of backend errors

This commit is contained in:
Chneemann 2025-04-07 12:51:57 +02:00
parent 0646aaae6b
commit c2c5bd850e
4 changed files with 31 additions and 4 deletions

View file

@ -79,7 +79,6 @@ export class LoginComponent {
this.loginData.email = this.loginData.email.toLowerCase();
try {
await this.authService.login(this.loginData, this.checkboxRememberMe);
this.router.navigate(['/summary']);
this.buttonStateService.enableButton();
} catch (error) {
this.buttonStateService.enableButton();

View file

@ -53,6 +53,11 @@ export class AuthInterceptor implements HttpInterceptor {
return next.handle(clonedReq).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 0 && !this.isNavigatingToLogin) {
this.tokenService.deleteAuthToken();
this.tokenService.deleteUserId();
this.router.navigate(['/login']);
}
if (error.status === 401 && !this.isNavigatingToLogin) {
this.toast.showSessionExpiredToast();
this.router.navigate(['/login']);

View file

@ -41,6 +41,7 @@ export class AuthService {
this.tokenService.storeUserId(userId, storage);
this.currentUserIdSubject.next(userId);
this.toastNotificationService.loginSuccessToast();
this.router.navigate(['/summary']);
} catch (error) {
console.error('Login failed:', error);
}
@ -65,8 +66,8 @@ export class AuthService {
await lastValueFrom(
this.apiService.request('POST', `/auth/register/`, credentials)
);
this.router.navigate(['/login']);
this.toastNotificationService.registerSuccessToast();
this.router.navigate(['/login']);
} catch (error: any) {
console.error('Registration failed:', error);
throw new Error(error?.error?.error);

View file

@ -7,8 +7,13 @@ import { ToastrService } from 'ngx-toastr';
})
export class ErrorNotificationService {
constructor(private toastr: ToastrService) {}
private isToastVisible = false;
handleHttpError(error: unknown): void {
if (this.isToastVisible) {
return;
}
let errorMessage = 'An unknown error occurred.';
if (error instanceof HttpErrorResponse) {
@ -22,8 +27,19 @@ export class ErrorNotificationService {
'The request could not be processed due to invalid input. Please check your entries and try again.';
break;
case 401:
errorMessage =
'The login credentials are incorrect. Please check your email and password.';
console.log(error);
if (
error.error.detail &&
(error.error.detail.includes('Token') ||
error.error.detail.includes('token'))
) {
errorMessage =
'The authentication token is invalid or expired. Please log in again.';
} else {
errorMessage =
'The login credentials are incorrect. Please check your email and password.';
}
break;
case 403:
errorMessage =
@ -59,10 +75,16 @@ export class ErrorNotificationService {
errorMessage = `Network error: ${error.message || error.toString()}`;
}
this.isToastVisible = true;
this.toastr.error(errorMessage, 'Error', {
timeOut: 3000,
positionClass: 'toast-top-right',
progressBar: true,
});
setTimeout(() => {
this.isToastVisible = false;
}, 3000);
}
}