From ce6b6751028bfe08b49628a30e660ff479eded02 Mon Sep 17 00:00:00 2001 From: Ian Bull Date: Wed, 4 Sep 2024 00:05:29 -0700 Subject: [PATCH] refactor(ext/fetch): align error messages (#25374) Aligns the error messages in the ext/fetch folder to be in-line with the Deno style guide. https://github.com/denoland/deno/issues/25269 --- ext/fetch/20_headers.js | 22 ++++++++--------- ext/fetch/21_formdata.js | 6 +++-- ext/fetch/22_body.js | 4 ++-- ext/fetch/23_response.js | 10 ++++---- ext/fetch/26_fetch.js | 10 ++++---- ext/fetch/fs_fetch_handler.rs | 2 +- ext/fetch/lib.rs | 24 +++++++++++-------- .../run/wasm_streaming_panic_test.js.out | 2 +- tests/unit/cache_api_test.ts | 2 +- tests/unit/fetch_test.ts | 4 ++-- tests/unit/headers_test.ts | 4 ++-- tests/unit/wasm_test.ts | 2 +- 12 files changed, 51 insertions(+), 41 deletions(-) diff --git a/ext/fetch/20_headers.js b/ext/fetch/20_headers.js index 1690d9f7d6f423..e56a74c4231221 100644 --- a/ext/fetch/20_headers.js +++ b/ext/fetch/20_headers.js @@ -73,7 +73,7 @@ function fillHeaders(headers, object) { const header = object[i]; if (header.length !== 2) { throw new TypeError( - `Invalid header. Length must be 2, but is ${header.length}`, + `Invalid header: length must be 2, but is ${header.length}`, ); } appendHeader(headers, header[0], header[1]); @@ -133,15 +133,15 @@ function appendHeader(headers, name, value) { // 2. if (!checkHeaderNameForHttpTokenCodePoint(name)) { - throw new TypeError("Header name is not valid."); + throw new TypeError(`Invalid header name: "${name}"`); } if (!checkForInvalidValueChars(value)) { - throw new TypeError("Header value is not valid."); + throw new TypeError(`Invalid header value: "${value}"`); } // 3. if (headers[_guard] == "immutable") { - throw new TypeError("Headers are immutable."); + throw new TypeError("Cannot change header: headers are immutable"); } // 7. @@ -330,10 +330,10 @@ class Headers { name = webidl.converters["ByteString"](name, prefix, "Argument 1"); if (!checkHeaderNameForHttpTokenCodePoint(name)) { - throw new TypeError("Header name is not valid."); + throw new TypeError(`Invalid header name: "${name}"`); } if (this[_guard] == "immutable") { - throw new TypeError("Headers are immutable."); + throw new TypeError("Cannot change headers: headers are immutable"); } const list = this[_headerList]; @@ -356,7 +356,7 @@ class Headers { name = webidl.converters["ByteString"](name, prefix, "Argument 1"); if (!checkHeaderNameForHttpTokenCodePoint(name)) { - throw new TypeError("Header name is not valid."); + throw new TypeError(`Invalid header name: "${name}"`); } const list = this[_headerList]; @@ -387,7 +387,7 @@ class Headers { name = webidl.converters["ByteString"](name, prefix, "Argument 1"); if (!checkHeaderNameForHttpTokenCodePoint(name)) { - throw new TypeError("Header name is not valid."); + throw new TypeError(`Invalid header name: "${name}"`); } const list = this[_headerList]; @@ -415,14 +415,14 @@ class Headers { // 2. if (!checkHeaderNameForHttpTokenCodePoint(name)) { - throw new TypeError("Header name is not valid."); + throw new TypeError(`Invalid header name: "${name}"`); } if (!checkForInvalidValueChars(value)) { - throw new TypeError("Header value is not valid."); + throw new TypeError(`Invalid header value: "${value}"`); } if (this[_guard] == "immutable") { - throw new TypeError("Headers are immutable."); + throw new TypeError("Cannot change headers: headers are immutable"); } const list = this[_headerList]; diff --git a/ext/fetch/21_formdata.js b/ext/fetch/21_formdata.js index bb33ea2d475710..7d466b8e255354 100644 --- a/ext/fetch/21_formdata.js +++ b/ext/fetch/21_formdata.js @@ -396,7 +396,9 @@ class MultipartParser { */ constructor(body, boundary) { if (!boundary) { - throw new TypeError("multipart/form-data must provide a boundary"); + throw new TypeError( + "Cannot construct MultipartParser: multipart/form-data must provide a boundary", + ); } this.boundary = `--${boundary}`; @@ -445,7 +447,7 @@ class MultipartParser { ) { return new FormData(); } - throw new TypeError("Unable to parse body as form data."); + throw new TypeError("Unable to parse body as form data"); } const formData = new FormData(); diff --git a/ext/fetch/22_body.js b/ext/fetch/22_body.js index 82f41411d86d7a..a8f5deac9c0364 100644 --- a/ext/fetch/22_body.js +++ b/ext/fetch/22_body.js @@ -151,7 +151,7 @@ class InnerBody { * @returns {Promise} */ consume() { - if (this.unusable()) throw new TypeError("Body already consumed."); + if (this.unusable()) throw new TypeError("Body already consumed"); if ( ObjectPrototypeIsPrototypeOf( ReadableStreamPrototype, @@ -372,7 +372,7 @@ function packageData(bytes, type, mimeType) { const boundary = mimeType.parameters.get("boundary"); if (boundary === null) { throw new TypeError( - "Missing boundary parameter in mime type of multipart formdata.", + "Cannot turn into form data: missing boundary parameter in mime type of multipart form data", ); } return parseFormData(chunkToU8(bytes), boundary); diff --git a/ext/fetch/23_response.js b/ext/fetch/23_response.js index 94fc69a9866627..7dad8c0472db69 100644 --- a/ext/fetch/23_response.js +++ b/ext/fetch/23_response.js @@ -172,7 +172,7 @@ function initializeAResponse(response, init, bodyWithType) { // 1. if ((init.status < 200 || init.status > 599) && init.status != 101) { throw new RangeError( - `The status provided (${init.status}) is not equal to 101 and outside the range [200, 599].`, + `The status provided (${init.status}) is not equal to 101 and outside the range [200, 599]`, ); } @@ -181,7 +181,9 @@ function initializeAResponse(response, init, bodyWithType) { init.statusText && RegExpPrototypeExec(REASON_PHRASE_RE, init.statusText) === null ) { - throw new TypeError("Status text is not valid."); + throw new TypeError( + `Invalid status text: "${init.statusText}"`, + ); } // 3. @@ -263,7 +265,7 @@ class Response { const baseURL = getLocationHref(); const parsedURL = new URL(url, baseURL); if (!redirectStatus(status)) { - throw new RangeError("Invalid redirect status code."); + throw new RangeError(`Invalid redirect status code: ${status}`); } const inner = newInnerResponse(status); inner.type = "default"; @@ -395,7 +397,7 @@ class Response { clone() { webidl.assertBranded(this, ResponsePrototype); if (this[_body] && this[_body].unusable()) { - throw new TypeError("Body is unusable."); + throw new TypeError("Body is unusable"); } const second = webidl.createBranded(Response); const newRes = cloneInnerResponse(this[_response]); diff --git a/ext/fetch/26_fetch.js b/ext/fetch/26_fetch.js index 47186fb2dd0bdc..8ac364a931c90f 100644 --- a/ext/fetch/26_fetch.js +++ b/ext/fetch/26_fetch.js @@ -99,7 +99,7 @@ function createResponseBodyStream(responseBodyRid, terminator) { async function mainFetch(req, recursive, terminator) { if (req.blobUrlEntry !== null) { if (req.method !== "GET") { - throw new TypeError("Blob URL fetch only supports GET method."); + throw new TypeError("Blob URL fetch only supports GET method"); } const body = new InnerBody(req.blobUrlEntry.stream()); @@ -145,7 +145,7 @@ async function mainFetch(req, recursive, terminator) { reqRid = resourceForReadableStream(stream, req.body.length); } } else { - throw new TypeError("invalid body"); + throw new TypeError("Invalid body"); } } @@ -441,13 +441,15 @@ function handleWasmStreaming(source, rid) { typeof contentType !== "string" || StringPrototypeToLowerCase(contentType) !== "application/wasm" ) { - throw new TypeError("Invalid WebAssembly content type."); + throw new TypeError("Invalid WebAssembly content type"); } } // 2.5. if (!res.ok) { - throw new TypeError(`HTTP status code ${res.status}`); + throw new TypeError( + `Failed to receive WebAssembly content: HTTP status code ${res.status}`, + ); } // Pass the resolved URL to v8. diff --git a/ext/fetch/fs_fetch_handler.rs b/ext/fetch/fs_fetch_handler.rs index 6f45ee664ebb4c..4c2b81f35645ec 100644 --- a/ext/fetch/fs_fetch_handler.rs +++ b/ext/fetch/fs_fetch_handler.rs @@ -43,7 +43,7 @@ impl FetchHandler for FsFetchHandler { Ok::<_, ()>(response) } .map_err(move |_| { - type_error("NetworkError when attempting to fetch resource.") + type_error("NetworkError when attempting to fetch resource") }) .or_cancel(&cancel_handle) .boxed_local(); diff --git a/ext/fetch/lib.rs b/ext/fetch/lib.rs index fa85824f440b34..a3f9eeb4fb6887 100644 --- a/ext/fetch/lib.rs +++ b/ext/fetch/lib.rs @@ -177,7 +177,7 @@ impl FetchHandler for DefaultFileFetchHandler { ) -> (CancelableResponseFuture, Option>) { let fut = async move { Ok(Err(type_error( - "NetworkError when attempting to fetch resource.", + "NetworkError when attempting to fetch resource", ))) }; (Box::pin(fut), None) @@ -361,14 +361,14 @@ where let (request_rid, cancel_handle_rid) = match scheme { "file" => { let path = url.to_file_path().map_err(|_| { - type_error("NetworkError when attempting to fetch resource.") + type_error("NetworkError when attempting to fetch resource") })?; let permissions = state.borrow_mut::(); permissions.check_read(&path, "fetch()")?; if method != Method::GET { return Err(type_error(format!( - "Fetching files only supports the GET method. Received {method}." + "Fetching files only supports the GET method: received {method}" ))); } @@ -394,7 +394,7 @@ where let uri = url .as_str() .parse::() - .map_err(|_| type_error("Invalid URL"))?; + .map_err(|_| type_error(format!("Invalid URL {url}")))?; let mut con_len = None; let body = if has_body { @@ -522,7 +522,9 @@ where // because the URL isn't an object URL. return Err(type_error("Blob for the given URL not found.")); } - _ => return Err(type_error(format!("scheme '{scheme}' not supported"))), + _ => { + return Err(type_error(format!("Url scheme '{scheme}' not supported"))) + } }; Ok(FetchReturn { @@ -586,7 +588,7 @@ pub async fn op_fetch_send( return Err(type_error(err.to_string())); } - Err(_) => return Err(type_error("request was cancelled")), + Err(_) => return Err(type_error("Request was cancelled")), }; let status = res.status(); @@ -1016,9 +1018,11 @@ pub fn create_http_client( let mut http_connector = HttpConnector::new(); http_connector.enforce_http(false); - let user_agent = user_agent - .parse::() - .map_err(|_| type_error("illegal characters in User-Agent"))?; + let user_agent = user_agent.parse::().map_err(|_| { + type_error(format!( + "Illegal characters in User-Agent: received {user_agent}" + )) + })?; let mut builder = hyper_util::client::legacy::Builder::new(TokioExecutor::new()); @@ -1060,7 +1064,7 @@ pub fn create_http_client( } (true, true) => {} (false, false) => { - return Err(type_error("Either `http1` or `http2` needs to be true")) + return Err(type_error("Cannot create Http Client: either `http1` or `http2` needs to be set to true")) } } diff --git a/tests/testdata/run/wasm_streaming_panic_test.js.out b/tests/testdata/run/wasm_streaming_panic_test.js.out index 8a3c68e3754af6..4ec523f1d01509 100644 --- a/tests/testdata/run/wasm_streaming_panic_test.js.out +++ b/tests/testdata/run/wasm_streaming_panic_test.js.out @@ -1,2 +1,2 @@ -error: Uncaught (in promise) TypeError: Invalid WebAssembly content type. +error: Uncaught (in promise) TypeError: Invalid WebAssembly content type at handleWasmStreaming (ext:deno_fetch/26_fetch.js:[WILDCARD]) diff --git a/tests/unit/cache_api_test.ts b/tests/unit/cache_api_test.ts index 792929870d3d46..08f768e3340fa7 100644 --- a/tests/unit/cache_api_test.ts +++ b/tests/unit/cache_api_test.ts @@ -118,7 +118,7 @@ Deno.test(async function cachePutReaderLock() { await response.arrayBuffer(); }, TypeError, - "Body already consumed.", + "Body already consumed", ); await promise; diff --git a/tests/unit/fetch_test.ts b/tests/unit/fetch_test.ts index 721b6912d581b2..35d5e563f42e17 100644 --- a/tests/unit/fetch_test.ts +++ b/tests/unit/fetch_test.ts @@ -1131,7 +1131,7 @@ Deno.test(function fetchResponseConstructorInvalidStatus() { assert(e instanceof RangeError); assert( e.message.endsWith( - "is not equal to 101 and outside the range [200, 599].", + "is not equal to 101 and outside the range [200, 599]", ), ); } @@ -1662,7 +1662,7 @@ Deno.test( ); }, TypeError, - "Fetching files only supports the GET method. Received POST.", + "Fetching files only supports the GET method: received POST", ); }, ); diff --git a/tests/unit/headers_test.ts b/tests/unit/headers_test.ts index ad453b67f69f48..ea72f784b5fa8c 100644 --- a/tests/unit/headers_test.ts +++ b/tests/unit/headers_test.ts @@ -406,11 +406,11 @@ Deno.test(function invalidHeadersFlaky() { assertThrows( () => new Headers([["x", "\u0000x"]]), TypeError, - "Header value is not valid.", + 'Invalid header value: "\u0000x"', ); assertThrows( () => new Headers([["x", "\u0000x"]]), TypeError, - "Header value is not valid.", + 'Invalid header value: "\u0000x"', ); }); diff --git a/tests/unit/wasm_test.ts b/tests/unit/wasm_test.ts index fab9c9308f88d9..e0db41ed0edb62 100644 --- a/tests/unit/wasm_test.ts +++ b/tests/unit/wasm_test.ts @@ -53,7 +53,7 @@ Deno.test( await assertRejects( () => wasmPromise, TypeError, - "Invalid WebAssembly content type.", + "Invalid WebAssembly content type", ); }, );