forked from microsoftgraph/msgraph-sdk-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponseHandler.ts
More file actions
74 lines (66 loc) · 2.61 KB
/
Copy pathResponseHandler.ts
File metadata and controls
74 lines (66 loc) · 2.61 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
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
74
import {GraphRequest} from "./GraphRequest"
import {GraphRequestCallback, GraphError} from "./common"
export class ResponseHandler {
static init(err, res, callback:GraphRequestCallback):void {
if (res && res.ok) { // 2xx
callback(null, res.body, res)
} else { // not OK response
if (err == null && res.error !== null) // if error was passed to body
callback(ResponseHandler.ParseError(res), null, res);
else // pass back error as first param
callback(ResponseHandler.ParseError(err), null, res)
}
}
/*
Example error for https://graph.microsoft.com/v1.0/me/events?$top=3&$search=foo
{
"error": {
"code": "SearchEvents",
"message": "The parameter $search is not currently supported on the Events resource.",
"innerError": {
"request-id": "b31c83fd-944c-4663-aa50-5d9ceb367e19",
"date": "2016-11-17T18:37:45"
}
}
}
*/
static ParseError(rawErr):GraphError {
let errObj; // path to object containing innerError (see above schema)
if (!('rawResponse' in rawErr)) { // if superagent correctly parsed the JSON
if (rawErr.response !== undefined && rawErr.response.body !== null && 'error' in rawErr.response.body) { // some 404s don't return an error object
errObj = rawErr.response.body.error;
}
} else {
// if there was an error parsing the JSON
// possibly because of http://stackoverflow.com/a/38749510/2517012
errObj = JSON.parse(rawErr.rawResponse.replace(/^\uFEFF/, '')).error;
}
// parse out statusCode
let statusCode:number;
if (rawErr.response !== undefined && rawErr.response.status !== undefined) {
statusCode = rawErr.response.status;
} else {
statusCode = rawErr.statusCode;
}
// if we couldn't find an error obj to parse, just return an object with a status code and date
if (errObj === undefined) {
return {
statusCode,
code: null,
message: null,
requestId: null,
date: new Date(),
body: null
}
}
let err:GraphError = {
statusCode,
code: errObj.code,
message: errObj.message,
requestId: errObj.innerError["request-id"],
date: new Date(errObj.innerError.date),
body: errObj
};
return err;
}
}