Commit 8fa70004 authored by nanahira's avatar nanahira

add exception service

parent 10dadea5
...@@ -13,7 +13,11 @@ export class AuthGuard implements CanActivate { ...@@ -13,7 +13,11 @@ export class AuthGuard implements CanActivate {
constructor(private userInfo: UserInfoService) {} constructor(private userInfo: UserInfoService) {}
async check() { async check() {
return !!this.userInfo.user; if (!this.userInfo.user) {
this.userInfo.login();
return false;
}
return true;
} }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
......
import { TestBed } from '@angular/core/testing';
import { ExceptionService } from './exception.service';
describe('ExceptionService', () => {
let service: ExceptionService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ExceptionService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { UserInfoService } from './user-info.service';
import { ToastService } from './toast.service';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class ExceptionService {
constructor(private toast: ToastService, private userInfo: UserInfoService) {}
handle(e: any, noRedirect = false) {
const error = e as HttpErrorResponse;
if (error.status === 401) {
if (!noRedirect) {
return undefined;
}
this.toast.warn('没有登录。');
this.userInfo.login();
} else {
this.toast.error(error.error?.message || error.message);
}
return undefined;
}
async run<T>(fun: () => T | Promise<T>): Promise<T | undefined> {
try {
return await fun();
} catch (e) {
this.handle(e);
return undefined;
}
}
}
...@@ -3,6 +3,7 @@ import { MyCardSSOUser } from './utility/MyCardSSOUser'; ...@@ -3,6 +3,7 @@ import { MyCardSSOUser } from './utility/MyCardSSOUser';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { loginUrl } from './utility/login-url'; import { loginUrl } from './utility/login-url';
import { Buffer } from 'buffer'; import { Buffer } from 'buffer';
import { ToastService } from './toast.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment