|
12 | 12 | // See the License for the specific language governing permissions and |
13 | 13 | // limitations under the License. |
14 | 14 |
|
| 15 | +import {GraphqlResponseError} from '@octokit/graphql'; |
15 | 16 | import {RequestError} from '@octokit/request-error'; |
16 | 17 | import {RequestError as RequestErrorBody} from '@octokit/types'; |
17 | 18 |
|
@@ -91,3 +92,56 @@ export class FileNotFoundError extends Error { |
91 | 92 | this.name = FileNotFoundError.name; |
92 | 93 | } |
93 | 94 | } |
| 95 | + |
| 96 | +/** |
| 97 | + * Type guard to check if an error is an Octokit RequestError. |
| 98 | + * |
| 99 | + * This function checks the structure of the error object to determine if it matches |
| 100 | + * the shape of a RequestError. It should be favored instead of `instanceof` checks, |
| 101 | + * especially in scenarios where the prototype chain might not be reliable, such as when |
| 102 | + * dealing with different versions of a package or when the error object might have been |
| 103 | + * modified. |
| 104 | + * |
| 105 | + * @param error The error object to check. |
| 106 | + * @returns A boolean indicating whether the error is a RequestError. |
| 107 | + */ |
| 108 | +export function isOctokitRequestError(error: unknown): error is RequestError { |
| 109 | + if (typeof error === 'object' && error !== null) { |
| 110 | + const e = error as RequestError; |
| 111 | + return ( |
| 112 | + e.name === 'HttpError' && |
| 113 | + typeof e.status === 'number' && |
| 114 | + typeof e.request === 'object' |
| 115 | + ); |
| 116 | + } |
| 117 | + return false; |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Type guard to check if an error is an Octokit GraphqlResponseError. |
| 122 | + * |
| 123 | + * This function checks the structure of the error object to determine if it matches |
| 124 | + * the shape of a GraphqlResponseError. It should be favored instead of `instanceof` checks, |
| 125 | + * especially in scenarios where the prototype chain might not be reliable, such as when |
| 126 | + * dealing with different versions of a package or when the error object might have been |
| 127 | + * modified. |
| 128 | + * |
| 129 | + * @param error The error object to check. |
| 130 | + * @returns A boolean indicating whether the error is a GraphqlResponseError. |
| 131 | + */ |
| 132 | +export function isOctokitGraphqlResponseError( |
| 133 | + error: unknown |
| 134 | +): error is GraphqlResponseError<unknown> { |
| 135 | + if (typeof error === 'object' && error !== null) { |
| 136 | + const e = error as GraphqlResponseError<unknown>; |
| 137 | + return ( |
| 138 | + typeof e.request === 'object' && |
| 139 | + typeof e.headers === 'object' && |
| 140 | + typeof e.response === 'object' && |
| 141 | + typeof e.name === 'string' && |
| 142 | + Array.isArray(e.errors) && |
| 143 | + e.data !== undefined |
| 144 | + ); |
| 145 | + } |
| 146 | + return false; |
| 147 | +} |
0 commit comments