-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Octokit error handling utility function
- Loading branch information
1 parent
ec3985e
commit 54c992c
Showing
2 changed files
with
49 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { RequestError } from "octokit"; | ||
|
||
function camelCaseToSentenceCase(str: string) { | ||
return str.replace( | ||
/([a-z])([A-Z])/g, | ||
(_, lower: string, upper: string) => `${lower} ${upper.toLowerCase()}` | ||
); | ||
} | ||
|
||
// TODO: figure out how to type this to restrict the method to only | ||
// those which are available on the `octokit.rest` instance | ||
|
||
/** | ||
* Calls an Octokit method, logging any errors that occur. | ||
* | ||
* @param method Octokit method to call | ||
* @param params parameters to pass to the method | ||
* | ||
* @returns the `data` property of the response | ||
* | ||
* @todo figure out how to type this to restrict the method to only those which are available on the `octokit.rest` instance | ||
*/ | ||
export async function safeOctokitRequest<Method extends (...args: any[]) => any>( | ||
method: Method, | ||
...params: Parameters<Method> | ||
): Promise<Awaited<ReturnType<Method>>["data"]> { | ||
try { | ||
const response = await method(params); | ||
return response.data; | ||
} catch (error) { | ||
if (error instanceof RequestError) { | ||
console.error( | ||
"Failed to %s: got HTTP %s response.", | ||
camelCaseToSentenceCase(method.name), | ||
error.status | ||
); | ||
} | ||
console.error(error); | ||
throw error; | ||
} | ||
} |