UNPKG

2.81 kBJavaScriptView Raw
1// Copyright © 2017, 2021 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16// fatal errors
17const codes = {
18 Error: 1,
19 InvalidOption: 2,
20 DatabaseNotFound: 10,
21 Unauthorized: 11,
22 Forbidden: 12,
23 DatabaseNotEmpty: 13,
24 NoLogFileName: 20,
25 LogDoesNotExist: 21,
26 IncompleteChangesInLogFile: 22,
27 SpoolChangesError: 30,
28 HTTPFatalError: 40,
29 BulkGetError: 50
30};
31
32class BackupError extends Error {
33 constructor(name, message) {
34 super(message);
35 this.name = name;
36 }
37}
38
39class HTTPError extends BackupError {
40 constructor(responseError, name) {
41 // Special case some names for more useful error messages
42 switch (responseError.status) {
43 case 401:
44 name = 'Unauthorized';
45 break;
46 case 403:
47 name = 'Forbidden';
48 break;
49 default:
50 name = name || 'HTTPFatalError';
51 }
52 super(name, responseError.message);
53 }
54}
55
56// Default function to return an error for HTTP status codes
57// < 400 -> OK
58// 4XX (except 429) -> Fatal
59// 429 & >=500 -> Transient
60function checkResponse(err) {
61 if (err) {
62 // Construct an HTTPError if there is request information on the error
63 // Codes < 400 are considered OK
64 if (err.status >= 400) {
65 return new HTTPError(err);
66 } else {
67 // Send it back again if there was no status code, e.g. a cxn error
68 return augmentMessage(err);
69 }
70 }
71}
72
73function convertResponseError(responseError, errorFactory) {
74 if (!errorFactory) {
75 errorFactory = checkResponse;
76 }
77 return errorFactory(responseError);
78}
79
80function augmentMessage(err) {
81 // For errors that don't have a status code, we are likely looking at a cxn
82 // error.
83 // Try to augment the message with more detail (core puts the code in statusText)
84 if (err && err.statusText) {
85 err.message = `${err.message} ${err.statusText}`;
86 }
87 if (err && err.description) {
88 err.message = `${err.message} ${err.description}`;
89 }
90 return err;
91}
92
93module.exports = {
94 BackupError: BackupError,
95 HTTPError: HTTPError,
96 convertResponseError: convertResponseError,
97 terminationCallback: function terminationCallback(err, data) {
98 if (err) {
99 console.error(`ERROR: ${err.message}`);
100 process.exitCode = codes[err.name] || 1;
101 process.exit();
102 }
103 }
104};