This repository was archived by the owner on Mar 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy patherrorHandler.js
82 lines (70 loc) · 1.85 KB
/
errorHandler.js
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
75
76
77
78
79
80
81
"use strict";
var createError = require('http-errors');
function _convertErrorName(errorId) {
errorId = errorId.charAt(0).toUpperCase() + errorId.slice(1);
return errorId.replace(/(\_\w)/g, function(m) {
return m[1].toUpperCase();
});
};
function _parseError(error) {
if (error.errors) {
return error.errors[0];
}
if (error.error) {
return {
id: error.error,
message: error.error_description
};
}
};
function handleHttpError(err, response, callback) {
if (!callback) {
throw new Error("no callback for http error handler- check method signature");
}
if (err) {
callback(err, null);
return true;
}
if (!response) {
callback(createError('no response'), null);
return true;
}
if (response.statusCode !== 200 &&
response.statusCode !== 201 &&
response.statusCode !== 204) {
var error;
try {
var errorBody = _parseError(JSON.parse(response.body));
error = createError(response.statusCode,
errorBody.message,
{name: _convertErrorName(errorBody.id)});
} catch (ex) {
error = createError(response.statusCode, response.body);
}
callback(error, null);
return true;
}
return false;
}
function handleError(err, obj, callback) {
if (!callback) {throw "no callback - check method signature";}
if (err) {
callback(err, null);
return true;
}
if (obj.error) {
callback(createError(obj.error, {name: 'APIError'}), null);
return true;
}
if (obj.errors) {
callback(createError(obj, {name: 'APIError'}), null);
return true;
}
if (obj.success !== undefined && obj.success !== true) {
callback(createError(obj, {name: 'APIError'}), null);
return true;
}
return false;
}
module.exports.handleError = handleError;
module.exports.handleHttpError = handleHttpError;