@@ -46,7 +46,10 @@ public function __construct( Data $settings, OpenAiClient $client ) {
46
46
* @param WC_Product $product The WooCommerce product to generate a description for.
47
47
*
48
48
* @return string The generated product description.
49
- * @throws Exception When an error occurs.
49
+ *
50
+ * @throws ClientException Is converted to an Exception.
51
+ * @throws Exception When no API key exists.
52
+ * @throws Exception When an API or moderation error occurs.
50
53
*/
51
54
public function generate ( WC_Product $ product ) {
52
55
$ settings = $ this ->settings ->get_settings ();
@@ -74,6 +77,9 @@ public function generate( WC_Product $product ) {
74
77
$ result = $ this ->client ->moderations ()->create (
75
78
new ModerationsRequest ( array ( 'input ' => $ prompt ) )
76
79
)->toArray ();
80
+ if ( array_key_exists ( 'error ' , $ result ) ) {
81
+ throw new ClientException ( $ result ['error ' ]['message ' ] );
82
+ }
77
83
78
84
$ flagged = (int ) $ result ['results ' ][0 ]['flagged ' ];
79
85
set_transient ( $ key , $ flagged , DAY_IN_SECONDS );
@@ -95,7 +101,7 @@ public function generate( WC_Product $product ) {
95
101
*
96
102
* @var array $result
97
103
*/
98
- $ result = $ completions ->create (
104
+ $ result = $ completions ->create (
99
105
new CompletionsRequest (
100
106
array (
101
107
'model ' => 'text-davinci-003 ' ,
@@ -105,6 +111,9 @@ public function generate( WC_Product $product ) {
105
111
)
106
112
)
107
113
)->toArray ();
114
+ if ( array_key_exists ( 'error ' , $ result ) ) {
115
+ throw new ClientException ( $ result ['error ' ]['message ' ] );
116
+ }
108
117
$ new_description = $ result ['choices ' ][0 ]['text ' ];
109
118
110
119
// Moderate the result.
@@ -117,6 +126,9 @@ public function generate( WC_Product $product ) {
117
126
$ result = $ this ->client ->moderations ()->create (
118
127
new ModerationsRequest ( array ( 'input ' => $ new_description ) )
119
128
)->toArray ();
129
+ if ( array_key_exists ( 'error ' , $ result ) ) {
130
+ throw new ClientException ( $ result ['error ' ]['message ' ] );
131
+ }
120
132
121
133
if ( $ result ['results ' ][0 ]['flagged ' ] ) {
122
134
throw new Exception (
0 commit comments