@@ -4,7 +4,7 @@ import type {
44 TokenEndpointResponse ,
55 TokenEndpointResponseHelpers ,
66} from 'openid-client' ;
7- import type { OIDCAbortSignal } from './types' ;
7+ import { MongoDBOIDCError , type OIDCAbortSignal } from './types' ;
88import { createHash , randomBytes } from 'crypto' ;
99
1010class AbortError extends Error {
@@ -235,3 +235,50 @@ export class TokenSet {
235235 . digest ( 'hex' ) ;
236236 }
237237}
238+
239+ // openid-client@6.x has reduced error messages for HTTP errors significantly, reducing e.g.
240+ // an HTTP error to just a simple 'unexpect HTTP response status code' message, without
241+ // further diagnostic information. So if the `cause` of an `err` object is a fetch `Response`
242+ // object, we try to throw a more helpful error.
243+ export async function improveHTTPResponseBasedError < T > (
244+ err : T
245+ ) : Promise < T | MongoDBOIDCError > {
246+ if (
247+ err &&
248+ typeof err === 'object' &&
249+ 'cause' in err &&
250+ err . cause &&
251+ typeof err . cause === 'object' &&
252+ 'status' in err . cause &&
253+ 'statusText' in err . cause &&
254+ 'text' in err . cause &&
255+ typeof err . cause . text === 'function'
256+ ) {
257+ try {
258+ let body = '' ;
259+ try {
260+ body = await err . cause . text ( ) ;
261+ } catch {
262+ // ignore
263+ }
264+ let errorMessageFromBody = '' ;
265+ try {
266+ const parsed = JSON . parse ( body ) ;
267+ errorMessageFromBody =
268+ ': ' + String ( parsed . error_description || parsed . error || '' ) ;
269+ } catch {
270+ // ignore
271+ }
272+ if ( ! errorMessageFromBody ) errorMessageFromBody = `: ${ body } ` ;
273+ return new MongoDBOIDCError (
274+ `${ errorString ( err ) } : caused by HTTP response ${ String (
275+ err . cause . status
276+ ) } (${ String ( err . cause . statusText ) } )${ errorMessageFromBody } `,
277+ { codeName : 'HTTPResponseError' , cause : err }
278+ ) ;
279+ } catch {
280+ return err ;
281+ }
282+ }
283+ return err ;
284+ }
0 commit comments