/
error.ts
73 lines (62 loc) · 1.95 KB
/
error.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Resource, properties } from './index.js';
export enum ErrorType {
Unauthorized = 'Unauthorized',
NotFound = 'NotFound',
Server = 'Server',
Client = 'Client',
}
/** Pass any error. If the error is an AtomicError and it's Unauthorized, return true */
export function isUnauthorized(error?: Error): boolean {
if (error instanceof AtomicError) {
if (error.type === ErrorType.Unauthorized) {
return true;
} else if (error.message.includes('Unauthorized')) {
return true;
}
}
return false;
}
/**
* Atomic Data Errors have an additional Type, which tells the client what kind
* of error to render.
*/
export class AtomicError extends Error {
public type: ErrorType;
/** Creates an AtomicError. The message can be either a plain string, or a JSON-AD Error Resource */
public constructor(message: string, type = ErrorType.Client) {
super(message);
// https://stackoverflow.com/questions/31626231/custom-error-class-in-typescript
Object.setPrototypeOf(this, AtomicError.prototype);
this.type = type;
this.message = message;
// The server should send Atomic Data Errors, which are JSON-AD resources with a Description.
try {
const parsed = JSON.parse(message);
const description = parsed[properties.description];
if (description) {
this.message = description;
}
} catch (e) {
// ignore
}
if (!this.message) {
this.message = this.createMessage();
}
}
public static fromResource(r: Resource): AtomicError {
const err = new AtomicError(r.get(properties.description)!.toString());
return err;
}
public createMessage(): string {
switch (this.type) {
case ErrorType.Unauthorized:
return "You don't have the rights to do this.";
case ErrorType.NotFound:
return '404 Not found.';
case ErrorType.Server:
return '500 Unknown server error.';
default:
return 'Unknown error.';
}
}
}