From d863a9c7b72cef5c239b1f34a94a61548e3ee4d8 Mon Sep 17 00:00:00 2001 From: lino-levan <11367844+lino-levan@users.noreply.github.com> Date: Tue, 16 May 2023 09:56:43 -0700 Subject: [PATCH] chore: throw error on error response --- README.md | 6 ++++-- src/openai.ts | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index fcaed7b..9da7042 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Unofficial Deno wrapper for the Open Ai API +# Unofficial Deno wrapper for the Open AI API [![Tags](https://img.shields.io/github/release/load1n9/openai)](https://github.com/load1n9/openai/releases) [![Doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/openai/mod.ts) @@ -7,7 +7,9 @@ ## Usage -Your Open AI Api key ([found here](https://beta.openai.com/account/api-keys)) is needed for this library to work. We recommend setting it as an environment variable. Here is a configuration example. +Your Open AI Api key ([found here](https://beta.openai.com/account/api-keys)) is +needed for this library to work. We recommend setting it as an environment +variable. Here is a configuration example. ```ts import { OpenAI } from "https://deno.land/x/openai/mod.ts"; diff --git a/src/openai.ts b/src/openai.ts index c60565c..2244760 100644 --- a/src/openai.ts +++ b/src/openai.ts @@ -29,7 +29,7 @@ import type { Translation, TranslationOptions, } from "./types.ts"; -import { basename } from "https://deno.land/std@0.185.0/path/mod.ts"; +import { basename } from "https://deno.land/std@0.187.0/path/mod.ts"; const defaultBaseUrl = "https://api.openai.com/v1"; @@ -65,8 +65,21 @@ export class OpenAI { method: options?.method ?? "POST", }, ); + const data = await response.json(); + + if (data.error) { + let errorMessage = `${data.error.type}`; + if (data.error.message) { + errorMessage += ": " + data.error.message; + } + if (data.error.code) { + errorMessage += ` (${data.error.code})`; + } + console.log(data.error); + throw new Error(errorMessage); + } - return await response.json(); + return data; } /**