1
- import { OpenAPIParseError , parseOpenAPI } from '@gitbook/openapi-parser' ;
1
+ import {
2
+ type Filesystem ,
3
+ OpenAPIParseError ,
4
+ type OpenAPIParseErrorCode ,
5
+ parseOpenAPI ,
6
+ } from '@gitbook/openapi-parser' ;
2
7
3
- import { noCacheFetchOptions } from '@/lib/data' ;
8
+ import { DataFetcherError , noCacheFetchOptions } from '@/lib/data' ;
4
9
import { resolveContentRef } from '@/lib/references' ;
5
10
import { unstable_cacheLife as cacheLife } from 'next/cache' ;
6
11
import { assert } from 'ts-essentials' ;
@@ -48,18 +53,35 @@ export async function fetchOpenAPIFilesystem(
48
53
} ;
49
54
}
50
55
51
- const fetchFilesystem = async ( url : string ) => {
56
+ const fetchFilesystem = async (
57
+ url : string
58
+ ) : Promise <
59
+ | Filesystem
60
+ | {
61
+ error : {
62
+ code : OpenAPIParseErrorCode ;
63
+ message : string ;
64
+ } ;
65
+ }
66
+ > => {
52
67
'use cache' ;
53
68
try {
54
69
return await fetchFilesystemUncached ( url ) ;
55
70
} catch ( error ) {
71
+ // To avoid hammering the file with requests, we cache the error for around a minute.
72
+ cacheLife ( 'minutes' ) ;
56
73
// Throwing an error inside a "use cache" function obfuscates the error,
57
74
// so we need to handle it here and recreates the error outside the cache function.
58
75
if ( error instanceof OpenAPIParseError ) {
59
- cacheLife ( 'seconds' ) ;
60
76
return { error : { code : error . code , message : error . message } } ;
61
77
}
62
- throw error ;
78
+ if ( error instanceof DataFetcherError ) {
79
+ return { error : { code : 'invalid' as const , message : 'Failed to fetch OpenAPI file' } } ;
80
+ }
81
+ // If the error is not an OpenAPIParseError or DataFetcherError,
82
+ // we assume it's an unknown error and return a generic error.
83
+ console . error ( 'Unknown error while fetching OpenAPI file:' , error ) ;
84
+ return { error : { code : 'invalid' as const , message : 'Unknown error' } } ;
63
85
}
64
86
} ;
65
87
@@ -78,7 +100,7 @@ async function fetchFilesystemUncached(
78
100
} ) ;
79
101
80
102
if ( ! response . ok ) {
81
- throw new Error ( ` Failed to fetch OpenAPI file: ${ response . status } ${ response . statusText } ` ) ;
103
+ throw new DataFetcherError ( ' Failed to fetch OpenAPI file' , response . status ) ;
82
104
}
83
105
84
106
const text = await response . text ( ) ;
0 commit comments