@@ -2,6 +2,7 @@ import type UndiciT from "undici";
2
2
3
3
import { CustomError } from "../error.js" ;
4
4
import { sanitizeUrl } from "../internal/request.js" ;
5
+ import { isObject } from "../lang.js" ;
5
6
6
7
export class RequestError extends CustomError {
7
8
constructor ( url : string , type : UndiciT . Dispatcher . HttpMethod , cause ?: Error ) {
@@ -41,10 +42,43 @@ export class ResponseStatusCodeError extends CustomError {
41
42
| null ;
42
43
public readonly body : null | Record < string , any > | string ;
43
44
44
- constructor ( url : string , cause : UndiciT . errors . ResponseStatusCodeError ) {
45
+ constructor ( url : string , cause : Error ) {
45
46
super ( `Received an unexpected status code from ${ sanitizeUrl ( url ) } ` , cause ) ;
46
- this . statusCode = cause . statusCode ;
47
- this . headers = cause . headers ;
48
- this . body = cause . body ;
47
+ this . statusCode =
48
+ "statusCode" in cause && typeof cause . statusCode === "number"
49
+ ? cause . statusCode
50
+ : - 1 ;
51
+ this . headers = this . #extractHeaders( cause ) ;
52
+ this . body = "body" in cause && isObject ( cause . body ) ? cause . body : null ;
53
+ }
54
+
55
+ #extractHeaders(
56
+ cause : Error ,
57
+ ) : string [ ] | Record < string , string | string [ ] | undefined > | null {
58
+ if ( "headers" in cause ) {
59
+ const headers = cause . headers ;
60
+ if ( Array . isArray ( headers ) ) {
61
+ return headers ;
62
+ } else if ( this . #isValidHeaders( headers ) ) {
63
+ return headers ;
64
+ }
65
+ }
66
+ return null ;
67
+ }
68
+
69
+ #isValidHeaders(
70
+ headers : unknown ,
71
+ ) : headers is Record < string , string | string [ ] | undefined > {
72
+ if ( ! isObject ( headers ) ) {
73
+ return false ;
74
+ }
75
+
76
+ return Object . values ( headers ) . every (
77
+ ( header ) =>
78
+ typeof header === "string" ||
79
+ ( Array . isArray ( header ) &&
80
+ header . every ( ( item : unknown ) => typeof item === "string" ) ) ||
81
+ header === undefined ,
82
+ ) ;
49
83
}
50
84
}
0 commit comments