UNPKG

1.15 kBJavaScriptView Raw
1'use strict'
2
3// We distinguish between errors thrown intentionally and uncaught exceptions
4// (such as bugs) with a `customErrorInfo.type` property.
5const throwUserError = function (messageOrError, error) {
6 const errorA = getError(messageOrError, error)
7 errorA[CUSTOM_ERROR_KEY] = { type: USER_ERROR_TYPE }
8 throw errorA
9}
10
11// Can pass either `message`, `error` or `message, error`
12const getError = function (messageOrError, error) {
13 if (messageOrError instanceof Error) {
14 return messageOrError
15 }
16
17 if (error === undefined) {
18 return new Error(messageOrError)
19 }
20
21 error.message = `${messageOrError}\n${error.message}`
22 return error
23}
24
25const isUserError = function (error) {
26 return (
27 canHaveErrorInfo(error) && error[CUSTOM_ERROR_KEY] !== undefined && error[CUSTOM_ERROR_KEY].type === USER_ERROR_TYPE
28 )
29}
30
31// Exceptions that are not objects (including `Error` instances) cannot have an
32// `CUSTOM_ERROR_KEY` property
33const canHaveErrorInfo = function (error) {
34 return error != null
35}
36
37const CUSTOM_ERROR_KEY = 'customErrorInfo'
38const USER_ERROR_TYPE = 'resolveConfig'
39
40module.exports = { throwUserError, isUserError }