This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
normalize-error-response.js
95 lines (92 loc) · 2.7 KB
/
normalize-error-response.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import Mixin from '@ember/object/mixin';
import { isArray } from '@ember/array';
import { isNone } from '@ember/utils';
import { merge } from '@ember/polyfills';
import isString from 'ember-ajax/-private/utils/is-string';
function isObject(object) {
return typeof object === 'object';
}
export default Mixin.create({
/**
* Normalize the error from the server into the same format
*
* The format we normalize to is based on the JSON API specification. The
* return value should be an array of objects that match the format they
* describe. More details about the object format can be found
* [here](http://jsonapi.org/format/#error-objects)
*
* The basics of the format are as follows:
*
* ```javascript
* [
* {
* status: 'The status code for the error',
* title: 'The human-readable title of the error'
* detail: 'The human-readable details of the error'
* }
* ]
* ```
*
* In cases where the server returns an array, then there should be one item
* in the array for each of the payload. If your server returns a JSON API
* formatted payload already, it will just be returned directly.
*
* If your server returns something other than a JSON API format, it's
* suggested that you override this method to convert your own errors into the
* one described above.
*
* @method normalizeErrorResponse
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Array} An array of JSON API-formatted error objects
*/
normalizeErrorResponse(status, headers, payload) {
payload = isNone(payload) ? {} : payload;
if (isArray(payload.errors)) {
return payload.errors.map(function(error) {
if (isObject(error)) {
const ret = merge({}, error);
ret.status = `${error.status}`;
return ret;
} else {
return {
status: `${status}`,
title: error
};
}
});
} else if (isArray(payload)) {
return payload.map(function(error) {
if (isObject(error)) {
return {
status: `${status}`,
title: error.title || 'The backend responded with an error',
detail: error
};
} else {
return {
status: `${status}`,
title: `${error}`
};
}
});
} else if (isString(payload)) {
return [
{
status: `${status}`,
title: payload
}
];
} else {
return [
{
status: `${status}`,
title: payload.title || 'The backend responded with an error',
detail: payload
}
];
}
}
});