nicer handling of login errors
Massimo Melina committed
Dec 20, 2021 at 15:40 UTC
dd1a59106d813f34345fc2043b5eba5b67359ec9
3 files changed
+11
-6
frontend/src/api.ts
+7
-1
@@ -11,10 +11,16 @@ export function apiCall(cmd: string, params?: object) : Promise<any> {
11
return res.json()
12
const msg = 'Failed API ' + cmd
13
console.warn(msg + (params ? ' ' + JSON.stringify(params) : ''))
14
- throw Error(msg)
14
+ throw new ApiError(res.status, msg)
15
})
16
}
17
18
+export class ApiError extends Error {
19
+ constructor(readonly code:number, message: string) {
20
+ super(message);
21
+ }
22
+}
23
+
24
export function useApi(cmd: string | Falsy, params?: object) : any {
25
const [x, setX] = useState()
26
useEffect(()=>{
frontend/src/login.ts
+4
-1
@@ -1,4 +1,4 @@
1
-import { apiCall } from './api'
1
+import { apiCall, ApiError } from './api'
2
import { state } from './state'
3
4
let refresher: NodeJS.Timeout
@@ -12,6 +12,9 @@ export async function login(user:string, password:string) {
12
state.username = user
13
}
14
catch(err) {
15
+ if (err instanceof ApiError)
16
+ if (err.code === 401)
17
+ err = 'Invalid credentials'
18
alert(err)
19
}
20
}
src/misc.ts
-4
@@ -6,10 +6,6 @@ export function enforceFinal(sub:string, s:string) {
6
return s.endsWith(sub) ? s : s+sub
7
}
8
9
-export function wantArray(x:any) {
10
- return x == null ? [] : Array.isArray(x) ? x : [x]
11
-}
12
-
9
export async function isDirectory(path: string) {
10
try { return (await fs.stat(path)).isDirectory() }
11
catch(e) { return false }