-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathdata-service-error.ts
More file actions
44 lines (40 loc) · 1.48 KB
/
data-service-error.ts
File metadata and controls
44 lines (40 loc) · 1.48 KB
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
import { EntityAction } from '../actions/entity-action';
import { RequestData } from './interfaces';
/**
* Error from a DataService
* The source error either comes from a failed HTTP response or was thrown within the service.
* @param error the HttpErrorResponse or the error thrown by the service
* @param requestData the HTTP request information such as the method and the url.
*/
export class DataServiceError extends Error {
constructor(public error: any, public requestData: RequestData | null) {
super(
typeof error === 'string' ? error : extractMessage(error) ?? undefined
);
this.name = this.constructor.name;
}
}
// Many ways the error can be shaped. These are the ways we recognize.
function extractMessage(sourceError: any): string | null {
const { error, body, message } = sourceError;
let errMessage: string | null = null;
if (error) {
// prefer HttpErrorResponse.error to its message property
errMessage = typeof error === 'string' ? error : error.message;
} else if (message) {
errMessage = message;
} else if (body) {
// try the body if no error or message property
errMessage = typeof body === 'string' ? body : body.error;
}
return typeof errMessage === 'string'
? errMessage
: errMessage
? JSON.stringify(errMessage)
: null;
}
/** Payload for an EntityAction data service error such as QUERY_ALL_ERROR */
export interface EntityActionDataServiceError {
error: DataServiceError;
originalAction: EntityAction;
}