diff --git a/conformance/README.md b/conformance/README.md new file mode 100644 index 0000000..f08db71 --- /dev/null +++ b/conformance/README.md @@ -0,0 +1,48 @@ +# Conformance vectors + +Language-neutral test data every http-error package must pass, so the same +error produces the same response in every language. Each package's test suite +reads these files directly; a change here runs every language's CI. + +## `vectors/problem-details.json` + +Three sections: + +- **`serialize`**: each case gives an error's `input` data and either the + `expected` response or an `error`. + - `input` members are the error's options: `status`, `message`, `title`, + `detail`, `type`, `instance`, `extensions`, `headers` and `expose`. A + missing member means the option is not set. + - `expected.status` is the response status; `expected.expose` is the error's + `expose` value; `expected.headers` is the complete set of response headers, + names lowercased, one value per name (no case repeats a header); + `expected.body` is the JSON response body. Compare bodies as JSON values: + member order is not significant. + - `error: "invalid status"` means constructing the error must fail. +- **`parse`**: each case gives a response `input` (`status` and the raw `body` + text) and the `expected` error read from it: `status`, `expose`, `title`, + `detail`, `type` and `instance` when present, and the remaining members as + `extensions`. The error's internal message is not pinned. +- **`defaults`**: for every status from 400 to 599, the `title` and `detail` + an error gets when neither is set and its message is not exposed. + +The rules the cases pin: + +- `status` is an integer from 400 to 599 and defaults to 500. +- `expose` defaults to true for 4xx and false for 5xx. +- `detail` is the explicit `detail` when given, else the `message` when the + error is exposed and the message is not empty, else the status's default. +- An empty string for `title`, `type`, `instance` or `message` counts as not + set, and so does an empty parsed `title` or `detail`. +- An extension named `type`, `status`, `title`, `detail` or `instance` is never + serialized. Any other member, `__proto__` included, is. +- `content-type` defaults to `application/problem+json`. +- Parsing ignores a leading UTF-8 byte-order mark. It takes the body's + `status` when it is a JSON number whose value is an integer from 400 to 599 + (`404`, `404.0` and `4.04e2` all count), else the response's status, else + 500. A member of the wrong JSON type, or `null`, is ignored. +- A parsed `detail` is the error's message, not an explicit detail: like any + message, it is public only when the error is exposed, so a 5xx problem's + detail is replaced by the default. +- A body that is not a JSON object with a non-null `status`, `title` or `type` + member gives an unexposed error with the default title and detail. diff --git a/conformance/vectors/problem-details.json b/conformance/vectors/problem-details.json new file mode 100644 index 0000000..809b9e3 --- /dev/null +++ b/conformance/vectors/problem-details.json @@ -0,0 +1,1703 @@ +{ + "description": "RFC 9457 Problem Details produced and parsed by every http-error package. See conformance/README.md.", + "serialize": [ + { + "name": "defaults to an unexposed 500", + "input": {}, + "expected": { + "status": 500, + "expose": false, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 500, + "title": "Internal Server Error", + "detail": "The server encountered an unexpected condition." + } + } + }, + { + "name": "exposes a client error's message as the detail", + "input": { + "status": 404, + "message": "No such user." + }, + "expected": { + "status": 404, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 404, + "title": "Not Found", + "detail": "No such user." + } + } + }, + { + "name": "hides a server error's message behind the status's generic detail", + "input": { + "status": 500, + "message": "SQL syntax error near 'users'" + }, + "expected": { + "status": 500, + "expose": false, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 500, + "title": "Internal Server Error", + "detail": "The server encountered an unexpected condition." + } + } + }, + { + "name": "sends an explicit detail even when the error is not exposed", + "input": { + "status": 503, + "message": "connection refused", + "detail": "Try again in a minute." + }, + "expected": { + "status": 503, + "expose": false, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 503, + "title": "Service Unavailable", + "detail": "Try again in a minute." + } + } + }, + { + "name": "hides a client error's message when expose is false", + "input": { + "status": 400, + "message": "row 12 failed the users_email_key constraint", + "expose": false + }, + "expected": { + "status": 400, + "expose": false, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 400, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error." + } + } + }, + { + "name": "exposes a server error's message when expose is true", + "input": { + "status": 502, + "message": "The upstream service timed out.", + "expose": true + }, + "expected": { + "status": 502, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 502, + "title": "Bad Gateway", + "detail": "The upstream service timed out." + } + } + }, + { + "name": "uses the generic detail for an exposed error with no message", + "input": { + "status": 409 + }, + "expected": { + "status": 409, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 409, + "title": "Conflict", + "detail": "The request conflicts with the current state of the resource." + } + } + }, + { + "name": "treats an empty message as no message", + "input": { + "status": 404, + "message": "" + }, + "expected": { + "status": 404, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 404, + "title": "Not Found", + "detail": "The requested resource could not be found." + } + } + }, + { + "name": "prefers an explicit detail to the exposed message", + "input": { + "status": 422, + "message": "email: invalid", + "detail": "Enter a valid email address." + }, + "expected": { + "status": 422, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 422, + "title": "Unprocessable Content", + "detail": "Enter a valid email address." + } + } + }, + { + "name": "uses a custom title", + "input": { + "status": 403, + "title": "Forbidden Access", + "message": "You cannot edit this project." + }, + "expected": { + "status": 403, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 403, + "title": "Forbidden Access", + "detail": "You cannot edit this project." + } + } + }, + { + "name": "serializes type, instance and extensions", + "input": { + "status": 400, + "message": "Invalid input", + "type": "/errors/validation", + "instance": "/requests/123", + "extensions": { + "field": "email", + "reasons": [ + "required" + ], + "retryable": false + } + }, + "expected": { + "status": 400, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "type": "/errors/validation", + "status": 400, + "title": "Bad Request", + "detail": "Invalid input", + "instance": "/requests/123", + "field": "email", + "reasons": [ + "required" + ], + "retryable": false + } + } + }, + { + "name": "never lets an extension replace a standard member", + "input": { + "status": 404, + "message": "No such user.", + "extensions": { + "type": "/x", + "status": 200, + "title": "x", + "detail": "x", + "instance": "/x", + "code": "user_missing" + } + }, + "expected": { + "status": 404, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 404, + "title": "Not Found", + "detail": "No such user.", + "code": "user_missing" + } + } + }, + { + "name": "adds the problem content type to custom headers", + "input": { + "status": 429, + "headers": { + "Retry-After": "30" + } + }, + "expected": { + "status": 429, + "expose": true, + "headers": { + "content-type": "application/problem+json", + "retry-after": "30" + }, + "body": { + "status": 429, + "title": "Too Many Requests", + "detail": "Too many requests have been sent in a given amount of time." + } + } + }, + { + "name": "keeps a custom content type", + "input": { + "status": 400, + "headers": { + "Content-Type": "application/json" + } + }, + "expected": { + "status": 400, + "expose": true, + "headers": { + "content-type": "application/json" + }, + "body": { + "status": 400, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error." + } + } + }, + { + "name": "accepts the lowest error status", + "input": { + "status": 400 + }, + "expected": { + "status": 400, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 400, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error." + } + } + }, + { + "name": "accepts the highest error status", + "input": { + "status": 599 + }, + "expected": { + "status": 599, + "expose": false, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 599, + "title": "Unknown Server Error", + "detail": "A server error occurred." + } + } + }, + { + "name": "names an unknown client status by its class", + "input": { + "status": 499 + }, + "expected": { + "status": 499, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 499, + "title": "Unknown Client Error", + "detail": "A client error occurred." + } + } + }, + { + "name": "names an unknown server status by its class", + "input": { + "status": 520, + "message": "origin error" + }, + "expected": { + "status": 520, + "expose": false, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 520, + "title": "Unknown Server Error", + "detail": "A server error occurred." + } + } + }, + { + "name": "treats an empty title, type and instance as not set", + "input": { + "status": 404, + "title": "", + "type": "", + "instance": "", + "message": "No such user." + }, + "expected": { + "status": 404, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 404, + "title": "Not Found", + "detail": "No such user." + } + } + }, + { + "name": "refuses status 399", + "input": { + "status": 399 + }, + "error": "invalid status" + }, + { + "name": "refuses status 600", + "input": { + "status": 600 + }, + "error": "invalid status" + }, + { + "name": "refuses status 200", + "input": { + "status": 200 + }, + "error": "invalid status" + }, + { + "name": "refuses status 404.5", + "input": { + "status": 404.5 + }, + "error": "invalid status" + } + ], + "parse": [ + { + "name": "reads every member of a problem", + "input": { + "status": 403, + "body": "{\"type\": \"/errors/forbidden\", \"status\": 403, \"title\": \"Forbidden Access\", \"detail\": \"You do not have permission.\", \"instance\": \"/projects/7\", \"code\": \"E1\"}" + }, + "expected": { + "status": 403, + "expose": true, + "title": "Forbidden Access", + "detail": "You do not have permission.", + "type": "/errors/forbidden", + "instance": "/projects/7", + "extensions": { + "code": "E1" + } + } + }, + { + "name": "takes the response status when the body has none", + "input": { + "status": 404, + "body": "{\"title\": \"Not Found\", \"detail\": \"No such user.\"}" + }, + "expected": { + "status": 404, + "expose": true, + "title": "Not Found", + "detail": "No such user.", + "extensions": {} + } + }, + { + "name": "prefers the body's status to the response's", + "input": { + "status": 400, + "body": "{\"status\": 422, \"detail\": \"Bad email.\"}" + }, + "expected": { + "status": 422, + "expose": true, + "title": "Unprocessable Content", + "detail": "Bad email.", + "extensions": {} + } + }, + { + "name": "takes the response status when the body's is not an error status", + "input": { + "status": 502, + "body": "{\"status\": 200, \"title\": \"Bad Gateway\"}" + }, + "expected": { + "status": 502, + "expose": false, + "title": "Bad Gateway", + "detail": "The server received an invalid response from an upstream server.", + "extensions": {} + } + }, + { + "name": "falls back to 500 when neither status is an error status", + "input": { + "status": 200, + "body": "{\"status\": \"oops\", \"title\": \"Strange\"}" + }, + "expected": { + "status": 500, + "expose": false, + "title": "Strange", + "detail": "The server encountered an unexpected condition.", + "extensions": {} + } + }, + { + "name": "uses the generic detail when a server problem has none", + "input": { + "status": 503, + "body": "{\"status\": 503}" + }, + "expected": { + "status": 503, + "expose": false, + "title": "Service Unavailable", + "detail": "The server is currently unavailable.", + "extensions": {} + } + }, + { + "name": "ignores members of the wrong type", + "input": { + "status": 400, + "body": "{\"status\": 400, \"title\": 7, \"detail\": false, \"type\": 1, \"instance\": null}" + }, + "expected": { + "status": 400, + "expose": true, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error.", + "extensions": {} + } + }, + { + "name": "hides the parse failure for a body that is not JSON", + "input": { + "status": 404, + "body": "Not Found" + }, + "expected": { + "status": 404, + "expose": false, + "title": "Not Found", + "detail": "The requested resource could not be found.", + "extensions": {} + } + }, + { + "name": "hides the parse failure for JSON that is not a problem", + "input": { + "status": 401, + "body": "{\"error\": \"invalid_token\"}" + }, + "expected": { + "status": 401, + "expose": false, + "title": "Unauthorized", + "detail": "Authentication is required to access this resource.", + "extensions": {} + } + }, + { + "name": "treats a JSON array as not a problem", + "input": { + "status": 400, + "body": "[{\"status\": 400}]" + }, + "expected": { + "status": 400, + "expose": false, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error.", + "extensions": {} + } + }, + { + "name": "gives a 500 for a successful response that is not a problem", + "input": { + "status": 200, + "body": "{\"ok\": true}" + }, + "expected": { + "status": 500, + "expose": false, + "title": "Internal Server Error", + "detail": "The server encountered an unexpected condition.", + "extensions": {} + } + }, + { + "name": "hides the detail of a server problem, which is its message", + "input": { + "status": 503, + "body": "{\"status\":503,\"detail\":\"db-internal.local:5432 refused\"}" + }, + "expected": { + "status": 503, + "expose": false, + "title": "Service Unavailable", + "detail": "The server is currently unavailable.", + "extensions": {} + } + }, + { + "name": "hides the detail of a client problem whose response is a server error", + "input": { + "status": 500, + "body": "{\"detail\":\"upstream said no\"}" + }, + "expected": { + "status": 500, + "expose": false, + "title": "Internal Server Error", + "detail": "The server encountered an unexpected condition.", + "extensions": {} + } + }, + { + "name": "reads an integer-valued status written with a fraction or exponent", + "input": { + "status": 400, + "body": "{\"status\":4.04e2,\"detail\":\"No such user.\"}" + }, + "expected": { + "status": 404, + "expose": true, + "title": "Not Found", + "detail": "No such user.", + "extensions": {} + } + }, + { + "name": "treats a fractional status as no status", + "input": { + "status": 409, + "body": "{\"status\":404.5,\"detail\":\"Conflict here.\"}" + }, + "expected": { + "status": 409, + "expose": true, + "title": "Conflict", + "detail": "Conflict here.", + "extensions": {} + } + }, + { + "name": "ignores a byte-order mark before the JSON", + "input": { + "status": 404, + "body": "{\"status\":404,\"detail\":\"No such user.\"}" + }, + "expected": { + "status": 404, + "expose": true, + "title": "Not Found", + "detail": "No such user.", + "extensions": {} + } + }, + { + "name": "treats empty title and detail strings as not set", + "input": { + "status": 404, + "body": "{\"status\":404,\"title\":\"\",\"detail\":\"\"}" + }, + "expected": { + "status": 404, + "expose": true, + "title": "Not Found", + "detail": "The requested resource could not be found.", + "extensions": {} + } + }, + { + "name": "treats null standard members as missing", + "input": { + "status": 404, + "body": "{\"status\":null,\"title\":null,\"type\":null,\"detail\":\"x\"}" + }, + "expected": { + "status": 404, + "expose": false, + "title": "Not Found", + "detail": "The requested resource could not be found.", + "extensions": {} + } + }, + { + "name": "keeps a __proto__ member as an extension", + "input": { + "status": 400, + "body": "{\"status\":400,\"__proto__\":{\"admin\":true}}" + }, + "expected": { + "status": 400, + "expose": true, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error.", + "extensions": { + "__proto__": { + "admin": true + } + } + } + } + ], + "defaults": [ + { + "status": 400, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error." + }, + { + "status": 401, + "title": "Unauthorized", + "detail": "Authentication is required to access this resource." + }, + { + "status": 402, + "title": "Payment Required", + "detail": "Payment is required to access this resource." + }, + { + "status": 403, + "title": "Forbidden", + "detail": "You do not have permission to access this resource." + }, + { + "status": 404, + "title": "Not Found", + "detail": "The requested resource could not be found." + }, + { + "status": 405, + "title": "Method Not Allowed", + "detail": "The request method is not supported for this resource." + }, + { + "status": 406, + "title": "Not Acceptable", + "detail": "The server cannot produce a response matching the acceptable values." + }, + { + "status": 407, + "title": "Proxy Authentication Required", + "detail": "Proxy authentication is required." + }, + { + "status": 408, + "title": "Request Timeout", + "detail": "The server timed out waiting for the request." + }, + { + "status": 409, + "title": "Conflict", + "detail": "The request conflicts with the current state of the resource." + }, + { + "status": 410, + "title": "Gone", + "detail": "The requested resource is no longer available." + }, + { + "status": 411, + "title": "Length Required", + "detail": "The request requires a Content-Length header." + }, + { + "status": 412, + "title": "Precondition Failed", + "detail": "A precondition in the request headers was not met." + }, + { + "status": 413, + "title": "Content Too Large", + "detail": "The request body is larger than the server is willing to process." + }, + { + "status": 414, + "title": "URI Too Long", + "detail": "The request URI is longer than the server is willing to process." + }, + { + "status": 415, + "title": "Unsupported Media Type", + "detail": "The request uses a media type that is not supported." + }, + { + "status": 416, + "title": "Range Not Satisfiable", + "detail": "The requested range cannot be satisfied." + }, + { + "status": 417, + "title": "Expectation Failed", + "detail": "The expectation in the Expect header cannot be met." + }, + { + "status": 418, + "title": "I'm a teapot", + "detail": "The server refuses to brew coffee because it is a teapot." + }, + { + "status": 419, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 420, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 421, + "title": "Misdirected Request", + "detail": "The request was directed at a server unable to produce a response." + }, + { + "status": 422, + "title": "Unprocessable Content", + "detail": "The request was well-formed but contained semantic errors." + }, + { + "status": 423, + "title": "Locked", + "detail": "The requested resource is locked." + }, + { + "status": 424, + "title": "Failed Dependency", + "detail": "The request failed due to a previous request failure." + }, + { + "status": 425, + "title": "Too Early", + "detail": "The server is unwilling to process a request that might be replayed." + }, + { + "status": 426, + "title": "Upgrade Required", + "detail": "The client must upgrade to a different protocol." + }, + { + "status": 427, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 428, + "title": "Precondition Required", + "detail": "The request must be conditional." + }, + { + "status": 429, + "title": "Too Many Requests", + "detail": "Too many requests have been sent in a given amount of time." + }, + { + "status": 430, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 431, + "title": "Request Header Fields Too Large", + "detail": "The request headers are too large." + }, + { + "status": 432, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 433, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 434, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 435, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 436, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 437, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 438, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 439, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 440, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 441, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 442, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 443, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 444, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 445, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 446, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 447, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 448, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 449, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 450, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 451, + "title": "Unavailable For Legal Reasons", + "detail": "The resource is unavailable for legal reasons." + }, + { + "status": 452, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 453, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 454, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 455, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 456, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 457, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 458, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 459, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 460, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 461, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 462, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 463, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 464, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 465, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 466, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 467, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 468, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 469, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 470, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 471, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 472, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 473, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 474, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 475, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 476, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 477, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 478, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 479, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 480, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 481, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 482, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 483, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 484, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 485, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 486, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 487, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 488, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 489, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 490, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 491, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 492, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 493, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 494, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 495, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 496, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 497, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 498, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 499, + "title": "Unknown Client Error", + "detail": "A client error occurred." + }, + { + "status": 500, + "title": "Internal Server Error", + "detail": "The server encountered an unexpected condition." + }, + { + "status": 501, + "title": "Not Implemented", + "detail": "The server does not support the functionality required." + }, + { + "status": 502, + "title": "Bad Gateway", + "detail": "The server received an invalid response from an upstream server." + }, + { + "status": 503, + "title": "Service Unavailable", + "detail": "The server is currently unavailable." + }, + { + "status": 504, + "title": "Gateway Timeout", + "detail": "The server did not receive a timely response from an upstream server." + }, + { + "status": 505, + "title": "HTTP Version Not Supported", + "detail": "The HTTP version used in the request is not supported." + }, + { + "status": 506, + "title": "Variant Also Negotiates", + "detail": "The server has an internal configuration error." + }, + { + "status": 507, + "title": "Insufficient Storage", + "detail": "The server has insufficient storage to complete the request." + }, + { + "status": 508, + "title": "Loop Detected", + "detail": "The server detected an infinite loop while processing the request." + }, + { + "status": 509, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 510, + "title": "Not Extended", + "detail": "Further extensions to the request are required." + }, + { + "status": 511, + "title": "Network Authentication Required", + "detail": "Network authentication is required to access this resource." + }, + { + "status": 512, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 513, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 514, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 515, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 516, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 517, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 518, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 519, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 520, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 521, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 522, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 523, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 524, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 525, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 526, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 527, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 528, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 529, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 530, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 531, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 532, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 533, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 534, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 535, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 536, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 537, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 538, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 539, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 540, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 541, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 542, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 543, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 544, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 545, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 546, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 547, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 548, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 549, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 550, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 551, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 552, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 553, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 554, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 555, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 556, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 557, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 558, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 559, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 560, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 561, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 562, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 563, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 564, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 565, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 566, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 567, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 568, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 569, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 570, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 571, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 572, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 573, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 574, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 575, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 576, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 577, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 578, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 579, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 580, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 581, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 582, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 583, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 584, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 585, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 586, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 587, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 588, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 589, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 590, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 591, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 592, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 593, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 594, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 595, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 596, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 597, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 598, + "title": "Unknown Server Error", + "detail": "A server error occurred." + }, + { + "status": 599, + "title": "Unknown Server Error", + "detail": "A server error occurred." + } + ] +} diff --git a/typescript/README.md b/typescript/README.md index b8fd4f0..79e3e01 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -56,7 +56,7 @@ Use it in any Node.js ES module. `HttpError` extends `Error`, so it works with import { HttpError } from "@udibo/http-error"; try { - throw new HttpError(404, "file not found"); + throw new HttpError({ status: 404, message: "file not found" }); } catch (error) { const httpError = HttpError.from(error); console.log(httpError.status); // 404 @@ -85,31 +85,36 @@ Below are some examples of how to use this module. ### HttpError -This class can be used on its own to create any `HttpError`. It has a few -different call signatures you can use. The 4 examples below would throw the same -error. +An `HttpError` is data: an HTTP status plus the +[RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) Problem Details members. +Create one from an options object; every option is optional. ```ts import { HttpError } from "@udibo/http-error"; -throw new HttpError(404, "file not found"); -throw new HttpError(404, { message: "file not found" }); -throw new HttpError("file not found", { status: 404 }); throw new HttpError({ status: 404, message: "file not found" }); ``` -You can also include a `cause` in the optional options argument for it like you -can with regular errors. Additional `HttpErrorOptions` include `statusText`, -`type` (a URI for the problem type), `instance` (a URI for this specific error -occurrence), `extensions` (an object for additional details), and `headers` (to -customize response headers). +| Option | Default | Meaning | +| ------------ | ----------------------------------------------- | ------------------------------------------------ | +| `status` | `500` | The HTTP status, an integer from 400 to 599 | +| `message` | `detail`, else `""` | The internal message, for logs | +| `title` | The status's reason phrase, such as `Not Found` | A short summary of the problem type | +| `detail` | See [`detail`](#detail) | The explanation sent to the client | +| `type` | none | A URI reference that identifies the problem type | +| `instance` | none | A URI reference that identifies this occurrence | +| `extensions` | `{}` | Extra Problem Details members | +| `headers` | `content-type: application/problem+json` | Response headers | +| `expose` | `true` for 4xx, `false` for 5xx | Whether the message is safe to show the client | +| `cause` | none | The error that caused this one, as on `Error` | ```ts -import { HttpError, type HttpErrorOptions } from "@udibo/http-error"; +import { HttpError } from "@udibo/http-error"; -const cause = new Error("Underlying issue"); -throw new HttpError(400, "Invalid input", { - cause, +throw new HttpError({ + status: 400, + message: "Invalid input", + cause: new Error("Underlying issue"), type: "/errors/validation-error", instance: "/requests/123/user-field", extensions: { field: "username", reason: "must be alphanumeric" }, @@ -117,260 +122,166 @@ throw new HttpError(400, "Invalid input", { }); ``` -All `HttpError` objects have a `status` associated with them. If a status is not -provided it will default to 500. The `expose` property will default to `true` -for client error statuses (4xx) and `false` for server error statuses (5xx). You -can override the default behavior by setting the `expose` property on the -options argument. - -For all known HTTP error status codes, a `name` will be generated (e.g., -`Not Found` for 404). If the name is not known, it will default to -`Unknown Client Error` or `Unknown Server Error`. +An error's `name` is its `title`, so logs and `toString()` read naturally: ```ts import { HttpError } from "@udibo/http-error"; -const error = new HttpError(404, "file not found"); +const error = new HttpError({ status: 404, message: "file not found" }); console.log(error.toString()); // Not Found: file not found -console.log(error.status); // 404 console.log(error.expose); // true ``` -If you would like to extend the `HttpError` class, you can pass your own error -name in the options. +The same options, and the responses they produce, are pinned by the +language-neutral vectors in +[`conformance/vectors/problem-details.json`](../conformance/vectors/problem-details.json), +which every language's package passes. + +#### `detail` + +`detail` is the message the client sees, so it is always safe to render. It +keeps internal details such as SQL errors and file paths out of responses: + +- An explicit `detail` option is always used. +- Otherwise, when the error is exposed and has a non-empty `message`, the + message is the detail. +- Otherwise the detail is a generic sentence for the status, such as "The + server encountered an unexpected condition." for 500. ```ts -import { HttpError, type HttpErrorOptions } from "@udibo/http-error"; +import { HttpError } from "@udibo/http-error"; -class CustomError extends HttpError { - constructor(message?: string, options?: HttpErrorOptions) { - super(message, { name: "CustomError", status: 420, ...options }); - } -} +new HttpError({ status: 400, message: "Invalid email format" }).detail; +// "Invalid email format" + +new HttpError({ status: 500, message: "Database connection refused" }).detail; +// "The server encountered an unexpected condition." + +new HttpError({ + status: 500, + message: "SQL syntax error", + detail: "An error occurred while processing your request.", +}).detail; +// "An error occurred while processing your request." ``` -#### `HttpError.from()` +When rendering an error in a page or template, use `error.detail`, never +`error.message`. Log `error.message` and `error.cause` for debugging. -This static method intelligently converts various error-like inputs into an -`HttpError` instance. +```ts +app.onError((cause, c) => { + const error = HttpError.from(cause); + console.error(`[${error.status}] ${error.message}`, error.cause); + return error.getResponse(); +}); +``` + +#### `HttpError.from()` -- If an `HttpError` is passed, it's returned directly. -- If an `Error` is passed, it's wrapped in a new `HttpError` (usually 500 - status), with the original error as the `cause`. -- If a `Response` object is passed, it attempts to parse the body as RFC 9457 - Problem Details. If successful, it creates an `HttpError` from those details. - If parsing fails or the body isn't Problem Details, it creates a generic - `HttpError` based on the response status. This method is asynchronous and - returns a `Promise`. -- If a `ProblemDetails` object is passed, it creates an `HttpError` from it. -- For other unknown inputs, it creates a generic `HttpError` with a 500 status. +Converts anything caught into an `HttpError`: + +- An `HttpError` is returned as is. +- An `Error` with a numeric `status`, such as a framework's HTTP exception, + keeps its status, message, cause, `expose`, `title`, `type`, `instance` and + `extensions`. Its `detail` and `headers` are not copied. +- Any other `Error` becomes an unexposed 500 whose `cause` is that error. +- A Problem Details object becomes the error it describes. Its `detail` + becomes the message, so a 5xx problem's detail stays private unless you + expose it. +- A `Response` is parsed as Problem Details and returns a `Promise`. A body + that is not Problem Details gives an unexposed error with the response's + status (500 when that is not an error status). +- Anything else becomes a 500 whose `cause` is that value. ```ts import { HttpError } from "@udibo/http-error"; -// From a standard Error -const plainError = new Error("Something went wrong"); -const httpErrorFromError = HttpError.from(plainError); -console.log(httpErrorFromError.status); // 500 -console.log(httpErrorFromError.message); // "Something went wrong" -console.log(httpErrorFromError.cause === plainError); // true - -// From a Response (example) -async function handleErrorResponse(response: Response) { - if (!response.ok) { - const error = await HttpError.from(response); - // Now 'error' is an HttpError instance - throw error; - } - return response.json(); -} +const fromError = HttpError.from(new Error("Something went wrong")); +console.log(fromError.status); // 500 -// From a ProblemDetails object -const problemDetails = { +const response = await fetch("/api/items/1"); +if (!response.ok) throw await HttpError.from(response); + +const fromDetails = HttpError.from({ status: 403, - title: "ForbiddenAccess", + title: "Forbidden Access", detail: "You do not have permission.", type: "/errors/forbidden", -}; -const httpErrorFromDetails = HttpError.from(problemDetails); -console.log(httpErrorFromDetails.status); // 403 -console.log(httpErrorFromDetails.name); // ForbiddenAccess +}); +console.log(fromDetails.title); // Forbidden Access ``` #### `HttpError.toJSON()` -This method returns a plain JavaScript object representing the error in the RFC -9457 Problem Details format. This is useful for serializing the error to a JSON -response body. The `detail` property is set to `exposedMessage`, which provides -a safe message for clients (see `exposedMessage` section below). +Returns the Problem Details object, which is also what `JSON.stringify` writes. +An extension named after a standard member (`type`, `status`, `title`, +`detail`, `instance`) is never serialized. ```ts import { HttpError } from "@udibo/http-error"; -const error = new HttpError(400, "Invalid input", { +const error = new HttpError({ + status: 400, + message: "Invalid input", type: "/errors/validation", instance: "/form/user", extensions: { field: "email" }, }); - -const problemDetails = error.toJSON(); -console.log(problemDetails); -// Outputs: +console.log(error.toJSON()); // { -// field: "email", +// type: "/errors/validation", // status: 400, // title: "Bad Request", // detail: "Invalid input", -// type: "/errors/validation", -// instance: "/form/user" -// } - -// For server errors (expose=false), detail uses a safe default message -const serverError = new HttpError(500, "SQL syntax error near 'users'"); -console.log(serverError.toJSON()); -// Outputs: -// { -// status: 500, -// title: "Internal Server Error", -// detail: "The server encountered an unexpected condition." +// instance: "/form/user", +// field: "email" // } ``` #### `HttpError.getResponse()` -This method returns a `Response` object, ready to be sent to the client. The -response body will be the JSON string of the Problem Details object (from -`toJSON()`), and headers (including `Content-Type: application/problem+json`) -will be set. The response status and status text will match the error's -properties. +Returns a `Response` with the error's status, its headers, and the JSON of +`toJSON()` as the body. ```ts import { HttpError } from "@udibo/http-error"; -const error = new HttpError(401, "Authentication required"); -const response = error.getResponse(); - +const response = new HttpError({ status: 401 }).getResponse(); console.log(response.status); // 401 console.log(response.headers.get("Content-Type")); // application/problem+json -// response.body can be read to get the JSON string ``` -#### `exposedMessage` - -The `exposedMessage` property provides a safe, user-friendly message that can be -exposed to clients. This prevents internal error details (like SQL errors, file -paths, or stack traces) from leaking to users. +### Custom errors -**How it works:** - -- If `exposedMessage` is explicitly provided in options, that value is used -- If `expose` is `true` and `message` exists, `exposedMessage` defaults to - `message` -- Otherwise, `exposedMessage` defaults to a generic message for the status code - (e.g., "The server encountered an unexpected condition." for 500) +Extend `HttpError` to give a family of errors its defaults. `instanceof` works +as usual. An error's `name` is its `title`, so assigning `this.name` in a +subclass changes the title clients see; set `title` instead. ```ts -import { HttpError } from "@udibo/http-error"; - -// Client error (expose=true by default) - message is used as exposedMessage -const clientError = new HttpError(400, "Invalid email format"); -console.log(clientError.exposedMessage); // "Invalid email format" - -// Server error (expose=false by default) - safe default is used -const serverError = new HttpError(500, "Database connection refused"); -console.log(serverError.exposedMessage); // "The server encountered an unexpected condition." -console.log(serverError.message); // "Database connection refused" (internal use only) - -// Custom exposedMessage - always takes priority -const customError = new HttpError(500, "SQL syntax error", { - exposedMessage: "An error occurred while processing your request.", -}); -console.log(customError.exposedMessage); // "An error occurred while processing your request." -``` - -### Server-Side Rendering Best Practices - -When rendering error messages in server-side templates or responses, always use -`error.exposedMessage` instead of `error.message` to prevent leaking internal -implementation details to users. - -**Why this matters:** - -- `error.message` may contain sensitive information (SQL errors, file paths, - stack traces) -- `error.exposedMessage` provides a safe, user-friendly message by default -- For server errors (5xx), the default `exposedMessage` is generic and safe -- For client errors (4xx), `exposedMessage` defaults to `message` since those - are typically user-facing - -**Example in a template:** - -```ts -// BAD - may expose internal details -

Error: ${error.message}

// "SQLSTATE[42S02]: Table 'users' doesn't exist" - -// GOOD - safe for users -

Error: ${error.exposedMessage}

// "The server encountered an unexpected condition." -``` - -**Example in error handling middleware:** - -```ts -app.onError((cause, c) => { - const error = HttpError.from(cause); - - // Log the full internal message for debugging - console.error(`[${error.status}] ${error.message}`, error.cause); - - // Return safe message to client (via toJSON which uses exposedMessage) - return error.getResponse(); -}); -``` - -### `createHttpErrorClass()` - -This factory function allows you to create custom error classes that extend -`HttpError`. You can provide default options (like `status`, `name`, `message`, -`extensions`, etc.) for your custom error class. - -```ts -import { createHttpErrorClass, type HttpErrorOptions } from "@udibo/http-error"; +import { HttpError, type HttpErrorOptions } from "@udibo/http-error"; -interface MyApiErrorExtensions { +interface ApiErrorExtensions { errorCode: string; - requestId?: string; } -const MyApiError = createHttpErrorClass({ - name: "MyApiError", // Default name - status: 452, // Default status - extensions: { - errorCode: "API_GENERAL_FAILURE", // Default extension value - }, -}); - -try { - throw new MyApiError("Specific operation failed.", { - extensions: { - errorCode: "API_OP_X_FAILED", // Override default extension - requestId: "req-123", // Add instance-specific extension - }, - }); -} catch (e) { - if (e instanceof MyApiError) { - console.log(e.name); // "MyApiError" - console.log(e.status); // 452 - console.log(e.message); // "Specific operation failed." - console.log(e.extensions.errorCode); // "API_OP_X_FAILED" - console.log(e.extensions.requestId); // "req-123" - // console.log(e.toJSON()); +class PaymentDeclinedError extends HttpError { + constructor( + message?: string, + options?: HttpErrorOptions, + ) { + super({ + status: 402, + title: "Payment Declined", + message, + ...options, + extensions: { errorCode: "card_declined", ...options?.extensions }, + }); } } -// Instance with overridden status -const anotherError = new MyApiError(453, "Another failure"); -console.log(anotherError.status); // 453 -console.log(anotherError.extensions.errorCode); // "API_GENERAL_FAILURE" (from default) +const error = new PaymentDeclinedError("Insufficient funds."); +console.log(error.status); // 402 +console.log(error.extensions.errorCode); // "card_declined" ``` ### Framework Integration @@ -401,7 +312,9 @@ app.get("/hono-error", () => { }); app.get("/http-error", () => { - throw new HttpError(400, "This is an example of an HttpError", { + throw new HttpError({ + status: 400, + message: "This is an example of an HttpError", type: "/errors/http-error", instance: "/errors/http-error/instance/123", extensions: { @@ -417,7 +330,7 @@ app.onError((cause) => { // Log the full internal error, including the cause console.error(error); - // The response body only contains the safe `exposedMessage` + // The response body only contains the safe `detail` return error.getResponse(); }); diff --git a/typescript/examples/hono.test.ts b/typescript/examples/hono.test.ts index bed3064..a0efd5d 100644 --- a/typescript/examples/hono.test.ts +++ b/typescript/examples/hono.test.ts @@ -29,7 +29,7 @@ describe("hono error handling", () => { expect(res.headers.get("content-type")).toBe("application/problem+json"); expect(await res.json()).toEqual({ status: 400, - title: "Error", + title: "Bad Request", detail: "This is an example of an error from hono", }); }); diff --git a/typescript/examples/hono.ts b/typescript/examples/hono.ts index 9435214..5027032 100644 --- a/typescript/examples/hono.ts +++ b/typescript/examples/hono.ts @@ -21,7 +21,9 @@ app.get("/hono-error", () => { }); app.get("/http-error", () => { - throw new HttpError(400, "This is an example of an HttpError", { + throw new HttpError({ + status: 400, + message: "This is an example of an HttpError", type: "/errors/http-error", instance: "/errors/http-error/instance/123", extensions: { diff --git a/typescript/scripts/npm-smoke.ts b/typescript/scripts/npm-smoke.ts index b5e7a81..2428f72 100644 --- a/typescript/scripts/npm-smoke.ts +++ b/typescript/scripts/npm-smoke.ts @@ -142,7 +142,6 @@ function readdirTarballs(directory: string): string[] { } const CONSUMER_SOURCE = `import { - createHttpErrorClass, HttpError, isHttpErrorLike, type HttpErrorOptions, @@ -159,18 +158,27 @@ function ok(value: unknown): void { if (!value) throw new Error("expected a truthy value"); } -const options: HttpErrorOptions<{ field: string }> = { extensions: { field: "email" } }; -const error = new HttpError(422, "bad field", options); +const options: HttpErrorOptions<{ field: string }> = { + status: 422, + message: "bad field", + extensions: { field: "email" }, +}; +const error = new HttpError(options); const details: ProblemDetails<{ field: string }> = error.toJSON(); equal(details.status, 422); -equal(details.title, "Unprocessable Entity"); +equal(details.title, "Unprocessable Content"); equal(details.field, "email"); ok(isHttpErrorLike(error)); -const NotFound = createHttpErrorClass({ status: 404, name: "MissingError" }); -const missing = new NotFound("gone"); +class MissingError extends HttpError { + constructor(message: string) { + super({ status: 404, title: "Missing", message }); + } +} +const missing = new MissingError("gone"); ok(missing instanceof HttpError); -equal(missing.name, "MissingError"); +equal(missing.name, "Missing"); +equal(missing.detail, "gone"); const response = error.getResponse(); equal(response.status, 422); diff --git a/typescript/src/conformance.test.ts b/typescript/src/conformance.test.ts new file mode 100644 index 0000000..c404afd --- /dev/null +++ b/typescript/src/conformance.test.ts @@ -0,0 +1,99 @@ +import { readFileSync } from "node:fs"; + +import { describe, expect, it } from "vitest"; + +import { HttpError, type HttpErrorOptions } from "./mod.ts"; + +interface SerializeCase { + name: string; + input: HttpErrorOptions; + expected?: { + status: number; + expose: boolean; + headers: Record; + body: Record; + }; + error?: "invalid status"; +} + +interface ParseCase { + name: string; + input: { status: number; body: string }; + expected: { + status: number; + expose: boolean; + title: string; + detail: string; + type?: string; + instance?: string; + extensions: Record; + }; +} + +const vectors = JSON.parse( + readFileSync( + new URL("../../conformance/vectors/problem-details.json", import.meta.url), + "utf8", + ), +) as { + serialize: SerializeCase[]; + parse: ParseCase[]; + defaults: { status: number; title: string; detail: string }[]; +}; + +describe("problem-details vectors: serialize", () => { + it.each(vectors.serialize.filter((vector) => vector.expected))( + "$name", + async ({ input, expected }) => { + const error = new HttpError(input); + const response = error.getResponse(); + expect({ + status: response.status, + expose: error.expose, + headers: Object.fromEntries(response.headers), + body: await response.json(), + }).toEqual(expected); + }, + ); + + it.each(vectors.serialize.filter((vector) => vector.error))( + "$name", + ({ input }) => { + expect(() => new HttpError(input)).toThrow(RangeError); + }, + ); +}); + +describe("problem-details vectors: parse", () => { + it.each(vectors.parse)("$name", async ({ input, expected }) => { + const error = await HttpError.from( + new Response(input.body, { status: input.status }), + ); + expect({ + status: error.status, + expose: error.expose, + title: error.title, + detail: error.detail, + ...(error.type === undefined ? {} : { type: error.type }), + ...(error.instance === undefined ? {} : { instance: error.instance }), + extensions: error.extensions, + }).toEqual(expected); + }); +}); + +describe("problem-details vectors: defaults", () => { + it("covers every error status", () => { + expect(vectors.defaults.map(({ status }) => status)).toEqual( + Array.from({ length: 200 }, (_, index) => 400 + index), + ); + }); + + it("gives every status its default title and detail", () => { + expect( + vectors.defaults.map(({ status }) => { + const { title, detail } = new HttpError({ status, expose: false }); + return { status, title, detail }; + }), + ).toEqual(vectors.defaults); + }); +}); diff --git a/typescript/src/mod.test.ts b/typescript/src/mod.test.ts index 4a7556e..4b18c3d 100644 --- a/typescript/src/mod.test.ts +++ b/typescript/src/mod.test.ts @@ -1,1260 +1,242 @@ import { describe, expect, it } from "vitest"; -import { - createHttpErrorClass, - HttpError, - type HttpErrorOptions, - isHttpErrorLike, -} from "./mod.ts"; - -const DEFAULT_ERROR_NAMES: Readonly> = { - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Auth Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Content Too Large", - 414: "URI Too Long", - 415: "Unsupported Media Type", - 416: "Range Not Satisfiable", - 417: "Expectation Failed", - 418: "I'm a teapot", - 421: "Misdirected Request", - 422: "Unprocessable Entity", - 423: "Locked", - 424: "Failed Dependency", - 425: "Too Early", - 426: "Upgrade Required", - 428: "Precondition Required", - 429: "Too Many Requests", - 431: "Request Header Fields Too Large", - 451: "Unavailable For Legal Reasons", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported", - 506: "Variant Also Negotiates", - 507: "Insufficient Storage", - 508: "Loop Detected", - 510: "Not Extended", - 511: "Network Authentication Required", -}; - -const DEFAULT_EXPOSED_MESSAGES: Readonly> = { - 400: "The server cannot process the request due to a client error.", - 401: "Authentication is required to access this resource.", - 402: "Payment is required to access this resource.", - 403: "You do not have permission to access this resource.", - 404: "The requested resource could not be found.", - 405: "The request method is not supported for this resource.", - 406: "The server cannot produce a response matching the acceptable values.", - 407: "Proxy authentication is required.", - 408: "The server timed out waiting for the request.", - 409: "The request conflicts with the current state of the resource.", - 410: "The requested resource is no longer available.", - 411: "The request requires a Content-Length header.", - 412: "A precondition in the request headers was not met.", - 413: "The request body is larger than the server is willing to process.", - 414: "The request URI is longer than the server is willing to process.", - 415: "The request uses a media type that is not supported.", - 416: "The requested range cannot be satisfied.", - 417: "The expectation in the Expect header cannot be met.", - 418: "The server refuses to brew coffee because it is a teapot.", - 421: "The request was directed at a server unable to produce a response.", - 422: "The request was well-formed but contained semantic errors.", - 423: "The requested resource is locked.", - 424: "The request failed due to a previous request failure.", - 425: "The server is unwilling to process a request that might be replayed.", - 426: "The client must upgrade to a different protocol.", - 428: "The request must be conditional.", - 429: "Too many requests have been sent in a given amount of time.", - 431: "The request headers are too large.", - 451: "The resource is unavailable for legal reasons.", - 500: "The server encountered an unexpected condition.", - 501: "The server does not support the functionality required.", - 502: "The server received an invalid response from an upstream server.", - 503: "The server is currently unavailable.", - 504: "The server did not receive a timely response from an upstream server.", - 505: "The HTTP version used in the request is not supported.", - 506: "The server has an internal configuration error.", - 507: "The server has insufficient storage to complete the request.", - 508: "The server detected an infinite loop while processing the request.", - 510: "Further extensions to the request are required.", - 511: "Network authentication is required to access this resource.", -}; - -function defaultErrorName(status: number): string { - return ( - DEFAULT_ERROR_NAMES[status] ?? - (status < 500 ? "Unknown Client Error" : "Unknown Server Error") - ); -} - -function defaultExposedMessage(status: number): string { - return ( - DEFAULT_EXPOSED_MESSAGES[status] ?? - (status < 500 ? "A client error occurred." : "A server error occurred.") - ); -} - -const statusRange = Array.from({ length: 200 }, (_, index) => 400 + index); +import { HttpError, isHttpErrorLike } from "./mod.ts"; describe("HttpError", () => { - it("defaults to a non-exposed 500 error without args", () => { - const error = new HttpError(); - expect(error.toString()).toBe("Internal Server Error"); - expect(error.name).toBe("Internal Server Error"); - expect(error.message).toBe(""); - expect(error.status).toBe(500); - expect(error.expose).toBe(false); - expect(error.cause).toBeUndefined(); - expect(error.extensions).toEqual({}); - expect(error.statusText).toBeUndefined(); - expect(error.type).toBeUndefined(); - expect(error.instance).toBeUndefined(); - expect(error.exposedMessage).toBe( - "The server encountered an unexpected condition.", - ); - }); - - it("is an Error whose name is not enumerable", () => { - const error = new HttpError(404, "missing"); + it("is an Error named by its title, with the name not enumerable", () => { + const error = new HttpError({ status: 404, message: "No such user." }); expect(error).toBeInstanceOf(Error); - expect(error).toBeInstanceOf(HttpError); + expect(error.name).toBe("Not Found"); + expect(String(error)).toBe("Not Found: No such user."); expect(Object.keys(error)).not.toContain("name"); + expect(error.stack).toContain("No such user."); }); - it.each([ - ["status", () => new HttpError(400)], - ["options", () => new HttpError({ status: 400 })], - [ - "undefined message and options", - () => new HttpError(undefined, { status: 400 }), - ], - ])("accepts a status through %s", (_label, create) => { - const error = create(); - expect(error.status).toBe(400); - expect(error.expose).toBe(true); + it("renames itself when its title changes", () => { + const error = new HttpError({ status: 400 }); + error.title = "Invalid Grant"; + expect(error.name).toBe("Invalid Grant"); }); - it.each([ - ["message", () => new HttpError("something went wrong")], - ["options", () => new HttpError({ message: "something went wrong" })], - [ - "undefined status and message", - () => new HttpError(undefined, "something went wrong"), - ], - [ - "undefined status and options", - () => new HttpError(undefined, { message: "something went wrong" }), - ], - ])("accepts a message through %s", (_label, create) => { - const error = create(); - expect(error.toString()).toBe( - "Internal Server Error: something went wrong", - ); - expect(error.message).toBe("something went wrong"); - expect(error.exposedMessage).toBe( - "The server encountered an unexpected condition.", + it("changes its title when its name is assigned, as a subclass may do", () => { + class NotFoundError extends HttpError { + constructor() { + super({ status: 404 }); + this.name = "NotFoundError"; + } + } + const error = new NotFoundError(); + expect([error.name, error.title]).toEqual([ + "NotFoundError", + "NotFoundError", + ]); + }); + + it("serializes an extension named __proto__ as a member", () => { + const extensions = JSON.parse('{"__proto__":{"admin":true}}') as Record< + string, + unknown + >; + expect( + JSON.parse( + JSON.stringify(new HttpError({ status: 400, extensions }).toJSON()), + ), + ).toEqual( + JSON.parse( + '{"status":400,"title":"Bad Request","detail":"The server cannot process the request due to a client error.","__proto__":{"admin":true}}', + ), ); }); - describe("status and message arguments take priority over options", () => { - const options = { message: "failed", status: 502 }; - - it.each([ - { - label: "status, message, options", - create: () => new HttpError(400, "something went wrong", options), - status: 400, - name: "Bad Request", - message: "something went wrong", - }, - { - label: "status, options", - create: () => new HttpError(400, options), - status: 400, - name: "Bad Request", - message: "failed", - }, - { - label: "message, options", - create: () => new HttpError("something went wrong", options), - status: 502, - name: "Bad Gateway", - message: "something went wrong", - }, - { - label: "options", - create: () => new HttpError(options), - status: 502, - name: "Bad Gateway", - message: "failed", - }, - ])("$label", ({ create, status, name, message }) => { - const error = create(); - expect(error.toString()).toBe(`${name}: ${message}`); - expect(error.name).toBe(name); - expect(error.message).toBe(message); - expect(error.status).toBe(status); - expect(error.expose).toBe(status < 500); + it("keeps the internal message apart from the public detail", () => { + const error = new HttpError({ + status: 500, + message: "connect ECONNREFUSED 10.0.0.5:5432", }); + expect(error.message).toBe("connect ECONNREFUSED 10.0.0.5:5432"); + expect(error.detail).toBe( + "The server encountered an unexpected condition.", + ); }); - it.each([ - ["options", (cause: Error) => new HttpError({ cause })], - ["status undefined", (cause: Error) => new HttpError(undefined, { cause })], - [ - "status and message undefined", - (cause: Error) => new HttpError(undefined, undefined, { cause }), - ], - ])("keeps the cause passed through %s", (_label, create) => { - const cause = new Error("fail"); - expect(create(cause).cause).toBe(cause); - }); - - it("keeps a falsy cause", () => { - expect(new HttpError({ cause: 0 }).cause).toBe(0); - expect(new HttpError({ cause: null }).cause).toBeNull(); - }); - - it.each([-500, 0, 399, 600, 1000])( - "throws a RangeError for the invalid status %i", - (status) => { - expect(() => new HttpError(status)).toThrow( - new RangeError("invalid error status"), - ); - expect(() => new HttpError(status)).toThrow(RangeError); - }, - ); - - it("accepts the boundary statuses 400 and 599", () => { - expect(new HttpError(400).status).toBe(400); - expect(new HttpError(599).status).toBe(599); - }); - - it("derives the default name from the status for every error status", () => { - const message = "something went wrong"; - for (const status of statusRange) { - const name = defaultErrorName(status); - const error = new HttpError(status, message); - expect([ - error.status, - error.name, - error.message, - error.toString(), - ]).toEqual([status, name, message, `${name}: ${message}`]); - } - }); - - it("names unknown statuses by class of error", () => { - expect(new HttpError(499).name).toBe("Unknown Client Error"); - expect(new HttpError(599).name).toBe("Unknown Server Error"); - }); - - it("overrides the name for every error status", () => { - const message = "something went wrong"; - for (const status of statusRange) { - const error = new HttpError(status, message, { name: "CustomError" }); - expect([error.status, error.name, error.toString()]).toEqual([ - status, - "CustomError", - `CustomError: ${message}`, - ]); - } + it("uses the detail as the message when no message is given", () => { + expect(new HttpError({ status: 400, detail: "Bad email." }).message).toBe( + "Bad email.", + ); }); - it("exposes only client errors by default", () => { - for (const status of statusRange) { - expect(new HttpError(status).expose).toBe(status < 500); - } + it("keeps a cause, even a falsy one, and sets none when not given", () => { + const cause = new Error("root"); + expect(new HttpError({ cause }).cause).toBe(cause); + const falsy = new HttpError({ cause: 0 }); + expect("cause" in falsy).toBe(true); + expect(falsy.cause).toBe(0); + expect("cause" in new HttpError()).toBe(false); }); - it("lets expose be overridden for every error status", () => { - for (const status of statusRange) { - const expose = status >= 500; - expect(new HttpError(status, { expose }).expose).toBe(expose); - } + it("accepts a Headers instance and copies it", () => { + const headers = new Headers({ "retry-after": "30" }); + const error = new HttpError({ status: 503, headers }); + expect(error.headers.get("retry-after")).toBe("30"); + expect(headers.has("content-type")).toBe(false); }); - describe("with all options", () => { - const cause = new Error("fail"); - const extensions = { key: "value" }; - - function allOptions(): HttpErrorOptions { - const headers = new Headers({ "X-Custom-Header": "TestValue" }); - headers.set("content-type", "application/custom+json"); - return { - name: "CustomErrorName", - message: "A very specific error occurred.", - status: 418, - statusText: "I'm a teapot", - expose: false, - cause, - type: "/errors/custom-operation-failed", - instance: "/errors/custom-operation-failed/instance/123xyz", - extensions, - headers, - }; - } - - it.each([ - { - signature: "status, message, options", - create: (options: HttpErrorOptions) => - new HttpError(418, "A very specific error occurred.", options), - }, - { - signature: "status, options", - create: (options: HttpErrorOptions) => - new HttpError(418, options), - }, - { - signature: "message, options", - create: ({ - message, - ...options - }: HttpErrorOptions) => - new HttpError(message, { ...options, status: 418 }), - }, - { - signature: "options", - create: (options: HttpErrorOptions) => - new HttpError(options), - }, - ])("constructor with $signature signature", ({ create }) => { - const error = create(allOptions()); - expect(error.name).toBe("CustomErrorName"); - expect(error.message).toBe("A very specific error occurred."); - expect(error.status).toBe(418); - expect(error.statusText).toBe("I'm a teapot"); - expect(error.expose).toBe(false); - expect(error.cause).toBe(cause); - expect(error.type).toBe("/errors/custom-operation-failed"); - expect(error.instance).toBe( - "/errors/custom-operation-failed/instance/123xyz", - ); - expect(error.extensions).toEqual(extensions); - expect(error.headers.get("X-Custom-Header")).toBe("TestValue"); - expect(error.headers.get("content-type")).toBe("application/custom+json"); - expect(error.toString()).toBe( - "CustomErrorName: A very specific error occurred.", - ); - }); + it("defaults extensions to an empty object of its own", () => { + const first = new HttpError(); + const second = new HttpError(); + expect(first.extensions).toEqual({}); + expect(first.extensions).not.toBe(second.extensions); }); - describe("headers", () => { - it("accepts a plain object and defaults the content type", () => { - const error = new HttpError({ - headers: { - "X-Custom-Test": "Value", - "X-Another-Header": "AnotherValue", - }, - }); - expect(error.headers.get("X-Custom-Test")).toBe("Value"); - expect(error.headers.get("X-Another-Header")).toBe("AnotherValue"); - expect(error.headers.get("content-type")).toBe( - "application/problem+json", - ); - }); - - it("keeps a content type given in a plain object", () => { - const error = new HttpError({ - headers: { - "X-Custom-Test": "Value", - "content-type": "application/custom+json", - }, - }); - expect(error.headers.get("X-Custom-Test")).toBe("Value"); - expect(error.headers.get("content-type")).toBe("application/custom+json"); - }); - - it("uses a Headers instance as given", () => { - const headers = new Headers({ "X-Custom-Test": "Value" }); - const error = new HttpError({ headers }); - expect(error.headers === headers).toBe(true); - expect(headers.get("content-type")).toBe("application/problem+json"); + it("serializes with JSON.stringify through toJSON", () => { + expect(JSON.parse(JSON.stringify(new HttpError({ status: 409 })))).toEqual({ + status: 409, + title: "Conflict", + detail: "The request conflicts with the current state of the resource.", }); - - it("defaults the content type to problem+json", () => { - expect(new HttpError().headers.get("content-type")).toBe( - "application/problem+json", - ); - }); - }); - - it("keeps other data in extensions", () => { - const cause = new Error("fail"); - const data = { x: 2, y: 3 }; - const errors = [ - new HttpError(400, "something went wrong", { - name: "CustomError", - expose: false, - cause, - extensions: data, - }), - new HttpError(400, { - name: "CustomError", - message: "something went wrong", - expose: false, - cause, - extensions: data, - }), - new HttpError("something went wrong", { - name: "CustomError", - status: 400, - expose: false, - cause, - extensions: data, - }), - new HttpError({ - name: "CustomError", - message: "something went wrong", - status: 400, - expose: false, - cause, - extensions: data, - }), - ]; - for (const error of errors) { - expect(error.toString()).toBe("CustomError: something went wrong"); - expect(error.name).toBe("CustomError"); - expect(error.message).toBe("something went wrong"); - expect(error.status).toBe(400); - expect(error.expose).toBe(false); - expect(error.cause).toBe(cause); - expect(error.extensions).toEqual(data); - } }); - describe("exposedMessage", () => { - it("uses the message when the error is exposed", () => { - const error = new HttpError(400, "Invalid email format"); - expect(error.message).toBe("Invalid email format"); - expect(error.exposedMessage).toBe("Invalid email format"); - expect(error.toJSON().detail).toBe("Invalid email format"); - }); - - it("uses the status default when an exposed error has no message", () => { - expect(new HttpError(404).exposedMessage).toBe( - "The requested resource could not be found.", - ); - }); - - it("uses the status default when the error is not exposed", () => { - const error = new HttpError(500, "SQL syntax error near 'DROP TABLE'"); - expect(error.exposedMessage).toBe( - "The server encountered an unexpected condition.", - ); - expect(error.toJSON().detail).toBe( - "The server encountered an unexpected condition.", - ); - }); - - it("uses the status default for a client error with expose false", () => { - const error = new HttpError(400, "private detail", { expose: false }); - expect(error.exposedMessage).toBe( - "The server cannot process the request due to a client error.", - ); - }); - - it("exposes the message of a server error with expose true", () => { - const error = new HttpError(503, "Down for maintenance", { - expose: true, - }); - expect(error.exposedMessage).toBe("Down for maintenance"); - }); - - it("has a default message for every known error status", () => { - for (const status of statusRange) { - expect(new HttpError(status).exposedMessage).toBe( - defaultExposedMessage(status), - ); + it("can be subclassed with defaults and still serialize", () => { + class InvalidGrantError extends HttpError<{ error: string }> { + constructor(message?: string) { + super({ + status: 400, + title: "Invalid Grant", + message, + extensions: { error: "invalid_grant" }, + }); } - }); - - it("falls back to a generic message for unknown statuses", () => { - expect(new HttpError(499).exposedMessage).toBe( - "A client error occurred.", - ); - expect(new HttpError(599).exposedMessage).toBe( - "A server error occurred.", - ); - }); - - it("prefers an explicit exposedMessage regardless of expose", () => { - const exposed = new HttpError(400, "Internal validation details", { - exposedMessage: "Please check your input.", - }); - expect(exposed.exposedMessage).toBe("Please check your input."); - expect(exposed.toJSON().detail).toBe("Please check your input."); - - const hidden = new HttpError(500, "Database connection refused", { - exposedMessage: "Service temporarily unavailable.", - }); - expect(hidden.exposedMessage).toBe("Service temporarily unavailable."); - expect(hidden.toJSON().detail).toBe("Service temporarily unavailable."); + } + const error = new InvalidGrantError("code expired"); + expect(error).toBeInstanceOf(HttpError); + expect(error.toJSON()).toEqual({ + status: 400, + title: "Invalid Grant", + detail: "code expired", + error: "invalid_grant", }); }); +}); - describe("toJSON", () => { - it("hides the message of an error converted from a plain Error", () => { - expect(HttpError.from(new Error("fail")).toJSON()).toEqual({ - title: "Internal Server Error", - status: 500, - detail: "The server encountered an unexpected condition.", - }); - }); - - it("exposes a client error with extensions", () => { - const data = { x: 2, y: 3 }; - const error = new HttpError(400, "something went wrong", { - name: "CustomError", - cause: new Error("fail"), - extensions: data, - }); - expect(error.toJSON()).toEqual({ - ...data, - title: "CustomError", - detail: "something went wrong", - status: 400, - }); - }); - - it("hides the message of a server error with extensions", () => { - const data = { x: 2, y: 3 }; - const error = new HttpError(500, "something went wrong", { - name: "CustomError", - cause: new Error("fail"), - extensions: data, - }); - expect(error.toJSON()).toEqual({ - ...data, - title: "CustomError", - status: 500, - detail: "The server encountered an unexpected condition.", - }); - }); - - it("hides the message of a client error that is explicitly not exposed", () => { - const data = { x: 2, y: 3 }; - const error = new HttpError(400, "something went wrong", { - name: "CustomError", - expose: false, - cause: new Error("fail"), - extensions: data, - }); - expect(error.toJSON()).toEqual({ - ...data, - title: "CustomError", - status: 400, - detail: "The server cannot process the request due to a client error.", - }); - }); - - it("omits type and instance when they are not set", () => { - const json = new HttpError(404, "missing").toJSON(); - expect(Object.keys(json).toSorted()).toEqual([ - "detail", - "status", - "title", - ]); - }); - - it("includes type and instance when they are set", () => { - const json = new HttpError(404, "missing", { - type: "/errors/missing", - instance: "/things/1", - }).toJSON(); - expect(json).toEqual({ - status: 404, - title: "Not Found", - detail: "missing", - type: "/errors/missing", - instance: "/things/1", - }); - }); - - it("lets the standard members override same-named extensions", () => { - const error = new HttpError(400, "real detail", { - extensions: { status: 200, title: "spoofed", detail: "spoofed" }, - }); - expect(error.toJSON()).toEqual({ - status: 400, - title: "Bad Request", - detail: "real detail", - }); - }); - - it("is used by JSON.stringify", () => { - const error = new HttpError(409, "conflict", { extensions: { id: 7 } }); - expect(JSON.parse(JSON.stringify(error))).toEqual({ - id: 7, - status: 409, - title: "Conflict", - detail: "conflict", - }); - }); +describe("HttpError.from", () => { + it("returns an HttpError unchanged", () => { + const error = new HttpError({ status: 418 }); + expect(HttpError.from(error)).toBe(error); }); - describe("getResponse", () => { - it("builds a response for an exposed client error with extensions, type, and instance", async () => { - const extensions = { extra: "data1" }; - const error = new HttpError(400, "Client Issue", { - name: "MyClientError", - extensions, - type: "/err/client", - instance: "/err/client/1", - }); - const response = error.getResponse(); - expect(response.status).toBe(400); - expect(response.headers.get("content-type")).toBe( - "application/problem+json", - ); - expect(await response.json()).toEqual({ - ...extensions, - status: 400, - title: "MyClientError", - detail: "Client Issue", - type: "/err/client", - instance: "/err/client/1", - }); - }); - - it("builds a response for a hidden server error with custom statusText and headers", async () => { - const extensions = { extra: "data2" }; - const headers = new Headers({ "X-RateLimit-Limit": "100" }); - headers.set("content-type", "application/vnd.api+json"); - const error = new HttpError(503, "Server Down", { - name: "CustomServerErr", - statusText: "Service Really Unavailable", - expose: false, - extensions, - headers, - }); - const response = error.getResponse(); - expect(response.status).toBe(503); - expect(response.statusText).toBe("Service Really Unavailable"); - expect(response.headers.get("content-type")).toBe( - "application/vnd.api+json", - ); - expect(response.headers.get("X-RateLimit-Limit")).toBe("100"); - expect(await response.json()).toEqual({ - ...extensions, - status: 503, - title: "CustomServerErr", - detail: "The server is currently unavailable.", - }); - }); - - it("defaults the content type and omits extensions", async () => { - const response = new HttpError(404, "Not Found").getResponse(); - expect(response.headers.get("content-type")).toBe( - "application/problem+json", - ); - expect(await response.json()).toEqual({ - status: 404, - title: "Not Found", - detail: "Not Found", - }); - }); - - it("leaves the response statusText empty when none is set", () => { - expect(new HttpError(404).getResponse().statusText).toBe(""); + it("keeps the data of an Error with a numeric status", () => { + const cause = new Error("root"); + const foreign = Object.assign(new Error("Slow down.", { cause }), { + status: 429, + title: "Rate Limited", + type: "/errors/rate-limit", + expose: false, + extensions: { limit: 10 }, }); - - it("round-trips through HttpError.from", async () => { - const error = new HttpError(422, "bad field", { - type: "/errors/validation", - instance: "/forms/1", - extensions: { field: "email" }, - }); - const roundTripped = await HttpError.from(error.getResponse()); - expect(roundTripped.status).toBe(422); - expect(roundTripped.name).toBe("Unprocessable Entity"); - expect(roundTripped.message).toBe("bad field"); - expect(roundTripped.type).toBe("/errors/validation"); - expect(roundTripped.instance).toBe("/forms/1"); - expect(roundTripped.extensions).toEqual({ field: "email" }); + const error = HttpError.from(foreign); + expect(error.toJSON()).toEqual({ + type: "/errors/rate-limit", + status: 429, + title: "Rate Limited", + detail: "Too many requests have been sent in a given amount of time.", + limit: 10, }); + expect(error.message).toBe("Slow down."); + expect(error.cause).toBe(cause); }); - describe("from", () => { - it("wraps a plain Error in a 500 HttpError with the error as cause", () => { - const cause = new Error("fail"); - const error = HttpError.from(cause); - expect(error.toString()).toBe("Internal Server Error: fail"); - expect(error.name).toBe("Internal Server Error"); - expect(error.message).toBe("fail"); - expect(error.status).toBe(500); - expect(error.expose).toBe(false); - expect(error.cause).toBe(cause); - expect(error.exposedMessage).toBe( - "The server encountered an unexpected condition.", - ); - }); - - it("converts an Error with a status, keeping its name", () => { - const original = Object.assign(new Error("fail"), { status: 400 }); - const error = HttpError.from(original); - expect(error).toBeInstanceOf(HttpError); - expect(error.toString()).toBe("Error: fail"); - expect(error.name).toBe("Error"); - expect(error.message).toBe("fail"); - expect(error.status).toBe(400); - expect(error.expose).toBe(true); - expect(error.cause).toBeUndefined(); - }); - - it("converts the old status-text-plus-Error name to the human-readable name", () => { - const original = Object.assign(new Error("gone"), { - name: "NotFoundError", - status: 404, - }); - expect(HttpError.from(original).name).toBe("Not Found"); - }); - - it("keeps a custom name that does not match the old format for its status", () => { - const original = Object.assign(new Error("gone"), { - name: "NotFoundError", - status: 410, - }); - expect(HttpError.from(original).name).toBe("NotFoundError"); - }); - - it("keeps an empty Error name as is", () => { - const original = Object.assign(new Error("odd"), { - name: "", - status: 404, - }); - expect(HttpError.from(original).name).toBe(""); - }); - - it("keeps a name for a status without status text", () => { - const original = Object.assign(new Error("odd"), { - name: "Error", - status: 499, - }); - expect(HttpError.from(original).name).toBe("Error"); - }); - - it("carries over the HttpError-like fields of an Error with a status", () => { - const cause = new Error("root"); - const original = Object.assign(new Error("fail"), { - status: 429, - expose: false, - cause, - type: "/errors/rate-limit", - instance: "/limits/1", - extensions: { retryAfter: 30 }, - exposedMessage: "Slow down.", - headers: new Headers({ "Retry-After": "30" }), - }); - const error = HttpError.from(original); - expect(error.status).toBe(429); - expect(error.expose).toBe(false); - expect(error.cause).toBe(cause); - expect(error.type).toBe("/errors/rate-limit"); - expect(error.instance).toBe("/limits/1"); - expect(error.extensions).toEqual({ retryAfter: 30 }); - expect(error.exposedMessage).toBe("Slow down."); - expect(error.headers.get("Retry-After")).toBe("30"); - }); - - it("returns an HttpError instance as is", () => { - const original = new HttpError({ - name: "CustomError", - message: "something went wrong", - cause: new Error("fail"), - extensions: { x: 2, y: 3 }, - }); - expect(HttpError.from(original) === original).toBe(true); - }); - - it.each([ - ["null", null], - ["undefined", undefined], - ["a number", 12345], - ["a boolean", true], - ["a string", "boom"], - ["a symbol", Symbol("test-symbol")], - ["an unrelated object", { completely: "unrelated object" }], - ["a function", () => {}], - ["an empty object", {}], - ])("wraps %s as an unexpected error type", (_label, input) => { - const error = HttpError.from(input); - expect(error).toBeInstanceOf(HttpError); - expect(error.status).toBe(500); - expect(error.message).toBe("unexpected error type"); - expect(error.cause).toBe(input); - }); - - it("converts a ProblemDetails object", () => { - const problemDetails = { - status: 404, - title: "ResourceNotFound", - detail: "The requested resource was not found.", - type: "/errors/not-found", - instance: "/items/123", - anotherKey: "anotherValue", - }; - const error = HttpError.from<{ anotherKey: string }>(problemDetails); - expect(error.status).toBe(404); - expect(error.name).toBe("ResourceNotFound"); - expect(error.message).toBe("The requested resource was not found."); - expect(error.type).toBe("/errors/not-found"); - expect(error.instance).toBe("/items/123"); - expect(error.extensions).toEqual({ anotherKey: "anotherValue" }); - expect(error.expose).toBe(true); - }); - - it("recognizes a ProblemDetails object that only has a title or type", () => { - expect(HttpError.from({ title: "Only Title", status: 400 }).name).toBe( - "Only Title", - ); - const byType = HttpError.from({ type: "/errors/only-type", status: 400 }); - expect(byType.type).toBe("/errors/only-type"); + it("sends neither a foreign error's detail nor its headers", () => { + const foreign = Object.assign(new Error("internal"), { + status: 500, + detail: "pg: password authentication failed for user admin", + headers: new Headers({ "set-cookie": "a=b", "content-length": "999" }), }); - - describe("Response", () => { - it("converts a ProblemDetails body", async () => { - const problemDetails = { - status: 403, - title: "ForbiddenError", - detail: "Access denied", - type: "/errors/forbidden", - instance: "/errors/forbidden/123", - customField: "customValue", - }; - const response = new Response(JSON.stringify(problemDetails), { - status: 403, - headers: { "Content-Type": "application/problem+json" }, - }); - const error = await HttpError.from(response); - expect(error.status).toBe(403); - expect(error.name).toBe("ForbiddenError"); - expect(error.message).toBe("Access denied"); - expect(error.type).toBe("/errors/forbidden"); - expect(error.instance).toBe("/errors/forbidden/123"); - expect(error.extensions).toEqual({ customField: "customValue" }); - expect(error.expose).toBe(true); - }); - - it("prefers the status in the body over the response status", async () => { - const response = new Response( - JSON.stringify({ - status: 403, - title: "ForbiddenError", - detail: "Access denied", - }), - { - status: 400, - headers: { "Content-Type": "application/problem+json" }, - }, - ); - const error = await HttpError.from(response); - expect(error.status).toBe(403); - expect(error.name).toBe("ForbiddenError"); - expect(error.message).toBe("Access denied"); - }); - - it("uses the response status when the body has none", async () => { - const response = new Response( - JSON.stringify({ title: "BadRequest", detail: "Bad input" }), - { - status: 400, - headers: { "Content-Type": "application/problem+json" }, - }, - ); - const error = await HttpError.from(response); - expect(error.status).toBe(400); - expect(error.name).toBe("BadRequest"); - expect(error.message).toBe("Bad input"); - }); - - it("reports a body that is not valid JSON", async () => { - const response = new Response("not json {{{{", { status: 500 }); - const error = await HttpError.from(response); - expect(error.status).toBe(500); - expect(error.message).toBe("could not parse problem details response"); - expect(error.cause).toBeInstanceOf(SyntaxError); - }); - - it("reports a body that was already consumed", async () => { - const response = new Response("{}", { status: 500 }); - await response.text(); - const error = await HttpError.from(response); - expect(error.status).toBe(500); - expect(error.message).toBe("could not parse problem details response"); - expect(error.cause).toBeInstanceOf(TypeError); - }); - - it("reports JSON that is not ProblemDetails", async () => { - const payload = { data: "some other structure" }; - const response = new Response(JSON.stringify(payload), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - const error = await HttpError.from(response); - expect(error.status).toBe(500); - expect(error.message).toBe("invalid problem details response"); - expect(error.cause).toEqual(payload); - }); - - it("reports a JSON body that is not an object", async () => { - const error = await HttpError.from( - new Response("null", { status: 502 }), - ); - expect(error.status).toBe(500); - expect(error.message).toBe("invalid problem details response"); - expect(error.cause).toBeNull(); - }); + const error = HttpError.from(foreign); + expect(error.detail).toBe( + "The server encountered an unexpected condition.", + ); + expect(Object.fromEntries(error.headers)).toEqual({ + "content-type": "application/problem+json", }); }); -}); -describe("createHttpErrorClass", () => { - it("creates a basic custom error class without default options", () => { - const BasicError = createHttpErrorClass(); - const error = new BasicError(400, "test message"); - expect(error).toBeInstanceOf(HttpError); - expect(error).toBeInstanceOf(BasicError); - expect(error.status).toBe(400); - expect(error.message).toBe("test message"); - expect(error.name).toBe("Bad Request"); - - const defaults = new BasicError(); - expect(defaults.status).toBe(500); - expect(defaults.message).toBe(""); - expect(defaults.name).toBe("Internal Server Error"); + it("keeps a server problem's detail as its unexposed message", () => { + const error = HttpError.from({ status: 500, detail: "secret internal" }); + expect([error.message, error.expose, error.detail]).toEqual([ + "secret internal", + false, + "The server encountered an unexpected condition.", + ]); }); - it("creates a custom error class with default name and status", () => { - const DefaultNameStatusError = createHttpErrorClass({ - name: "MyTestError", - status: 499, - }); - - const byMessage = new DefaultNameStatusError("A message"); - expect(byMessage.status).toBe(499); - expect(byMessage.name).toBe("MyTestError"); - expect(byMessage.message).toBe("A message"); - - const byStatus = new DefaultNameStatusError(498, "Override status"); - expect(byStatus.status).toBe(498); - expect(byStatus.name).toBe("MyTestError"); - expect(byStatus.message).toBe("Override status"); - - const byOptions = new DefaultNameStatusError({ - message: "Via options", - name: "OverriddenName", - }); - expect(byOptions.status).toBe(499); - expect(byOptions.name).toBe("OverriddenName"); - expect(byOptions.message).toBe("Via options"); - - const byStatusOption = new DefaultNameStatusError({ status: 497 }); - expect(byStatusOption.status).toBe(497); - expect(byStatusOption.name).toBe("MyTestError"); - expect(byStatusOption.message).toBe(""); + it("does not take a foreign error's name as the title", () => { + const foreign = Object.assign(new TypeError("bad"), { status: 400 }); + expect(HttpError.from(foreign).title).toBe("Bad Request"); }); - it("merges default extensions with instance extensions", () => { - interface MyExt { - defaultKey: string; - anotherKey?: number; - yetAnotherKey?: string; - } - const ExtError = createHttpErrorClass({ - extensions: { defaultKey: "defaultValue", yetAnotherKey: "stillHere" }, - }); - - const defaults = new ExtError("msg"); - expect(defaults.extensions.defaultKey).toBe("defaultValue"); - expect(defaults.extensions.yetAnotherKey).toBe("stillHere"); - expect(defaults.extensions.anotherKey).toBeUndefined(); - - const merged = new ExtError("msg", { - extensions: { defaultKey: "override", anotherKey: 123 }, - }); - expect(merged.extensions.defaultKey).toBe("override"); - expect(merged.extensions.anotherKey).toBe(123); - expect((merged.extensions as MyExt).yetAnotherKey).toBe("stillHere"); - - const byOptions = new ExtError({ - extensions: { - anotherKey: 456, - defaultKey: "defaultValue", - yetAnotherKey: "stillHere", - }, - }); - expect(byOptions.extensions.defaultKey).toBe("defaultValue"); - expect(byOptions.extensions.anotherKey).toBe(456); - expect(byOptions.extensions.yetAnotherKey).toBe("stillHere"); - expect(byOptions.message).toBe(""); - expect(byOptions.status).toBe(500); - - const WithStatus = createHttpErrorClass({ - status: 420, - extensions: { defaultKey: "val" }, - }); - const withStatus = new WithStatus(); - expect(withStatus.status).toBe(420); - expect(withStatus.extensions.defaultKey).toBe("val"); + it("gives a 500 for an Error with a status that is not an error status", () => { + const foreign = Object.assign(new Error("moved"), { status: 302 }); + expect(HttpError.from(foreign).status).toBe(500); }); - it("does not share default extensions between instances", () => { - const SharedDefaults = createHttpErrorClass<{ - list: string[]; - id?: string; - }>({ - extensions: { list: [] }, - }); - const first = new SharedDefaults({ extensions: { list: [], id: "a" } }); - const second = new SharedDefaults(); - expect(second.extensions.id).toBeUndefined(); - expect(first.extensions).not.toBe(second.extensions); + it("wraps any other Error as an unexposed 500 caused by it", () => { + const cause = new Error("boom"); + const error = HttpError.from(cause); + expect([error.status, error.expose, error.message, error.cause]).toEqual([ + 500, + false, + "boom", + cause, + ]); }); - describe("with all possible default options", () => { - interface AllExt { - id: string; - type?: string; - newProp?: string; - } - const defaultHeaders = new Headers({ "X-Default": "true" }); - const defaultCause = new Error("Default cause"); - - const AllDefaultsError = createHttpErrorClass({ - name: "AllDefaultsErrorName", - status: 488, - message: "Default message for error", - expose: true, - statusText: "Default Status Text Here", - type: "/errors/all-defaults-type", - instance: "/errors/all-defaults-instance/0", - extensions: { id: "default-id", type: "default-ext-type" }, - headers: defaultHeaders, - cause: defaultCause, - exposedMessage: "Default exposed message", - }); - - it("applies every default when instantiated without arguments", () => { - const error = new AllDefaultsError(); - expect(error.name).toBe("AllDefaultsErrorName"); - expect(error.status).toBe(488); - expect(error.message).toBe("Default message for error"); - expect(error.expose).toBe(true); - expect(error.statusText).toBe("Default Status Text Here"); - expect(error.type).toBe("/errors/all-defaults-type"); - expect(error.instance).toBe("/errors/all-defaults-instance/0"); - expect(error.extensions.id).toBe("default-id"); - expect(error.extensions.type).toBe("default-ext-type"); - expect(error.headers.get("X-Default")).toBe("true"); - expect(error.cause).toBe(defaultCause); - expect(error.exposedMessage).toBe("Default exposed message"); - }); - - it("lets status and message arguments override the defaults", () => { - const error = new AllDefaultsError(489, "New message from args"); - expect(error.status).toBe(489); - expect(error.message).toBe("New message from args"); - expect(error.name).toBe("AllDefaultsErrorName"); - expect(error.extensions.id).toBe("default-id"); - }); - - it("lets an options object override some defaults and keep the rest", () => { - const instanceHeaders = new Headers({ "X-Instance": "live" }); - const instanceCause = new Error("Instance cause here"); - const error = new AllDefaultsError({ - name: "InstanceNameOverride", - message: "Instance message in options", - expose: false, - extensions: { id: "instance-id-override", newProp: "instanceValue" }, - headers: instanceHeaders, - cause: instanceCause, - type: "/errors/instance-type-override", - exposedMessage: "Instance exposed message", - }); - expect(error.name).toBe("InstanceNameOverride"); - expect(error.status).toBe(488); - expect(error.message).toBe("Instance message in options"); - expect(error.expose).toBe(false); - expect(error.statusText).toBe("Default Status Text Here"); - expect(error.type).toBe("/errors/instance-type-override"); - expect(error.instance).toBe("/errors/all-defaults-instance/0"); - expect(error.extensions.id).toBe("instance-id-override"); - expect((error.extensions as AllExt).type).toBe("default-ext-type"); - expect(error.extensions.newProp).toBe("instanceValue"); - expect(error.headers.get("X-Instance")).toBe("live"); - expect(error.headers.has("X-Default")).toBe(false); - expect(error.cause).toBe(instanceCause); - expect(error.exposedMessage).toBe("Instance exposed message"); - }); - - it("lets an instance override the default instance", () => { - const error = new AllDefaultsError({ instance: "/instances/9" }); - expect(error.instance).toBe("/instances/9"); - }); - - describe("statusText overrides", () => { - it("uses statusText from the options", () => { - const error = new AllDefaultsError({ - statusText: "Overridden Status Text Via Options", - }); - expect(error.statusText).toBe("Overridden Status Text Via Options"); - expect(error.status).toBe(488); - expect(error.name).toBe("AllDefaultsErrorName"); - }); - - it("uses statusText from the options when a status argument is present", () => { - const error = new AllDefaultsError(490, { - statusText: "Custom StatusText with Status Arg", - }); - expect(error.status).toBe(490); - expect(error.statusText).toBe("Custom StatusText with Status Arg"); - }); - - it("uses statusText from the options when a message argument is present", () => { - const error = new AllDefaultsError("A message", { - statusText: "Custom StatusText with Message Arg", - }); - expect(error.message).toBe("A message"); - expect(error.statusText).toBe("Custom StatusText with Message Arg"); - expect(error.status).toBe(488); - }); - - it("uses statusText from the options when status and message arguments are present", () => { - const error = new AllDefaultsError(491, "A full message", { - statusText: "Custom StatusText with Full Args", - }); - expect(error.status).toBe(491); - expect(error.message).toBe("A full message"); - expect(error.statusText).toBe("Custom StatusText with Full Args"); - }); - - it("keeps the class default statusText when the options have none", () => { - const error = new AllDefaultsError({ - message: "Message without status text override", - }); - expect(error.statusText).toBe("Default Status Text Here"); - expect(new AllDefaultsError().statusText).toBe( - "Default Status Text Here", - ); - }); + it("reads a Problem Details object", () => { + const error = HttpError.from({ + status: 403, + title: "Forbidden Access", + detail: "You do not have permission.", + code: "E1", }); + expect([error.status, error.title, error.detail, error.message]).toEqual([ + 403, + "Forbidden Access", + "You do not have permission.", + "You do not have permission.", + ]); + expect(error.extensions).toEqual({ code: "E1" }); }); - it("creates instances that behave like HttpError for toJSON and getResponse", async () => { - interface RespExt { - code: number; - field?: string; - defaultInfo?: string; - } - const RespError = createHttpErrorClass({ - name: "RespTestError", - status: 422, - extensions: { code: 100, defaultInfo: "from_default" }, - expose: true, - }); - - const error = new RespError("Validation failed", { - extensions: { code: 101, field: "email" }, - type: "/errors/validation", - instance: "/user/123/email", - }); - - const json = error.toJSON(); - expect(json).toEqual({ - status: 422, - title: "RespTestError", - detail: "Validation failed", - type: "/errors/validation", - instance: "/user/123/email", - code: 101, - field: "email", - defaultInfo: "from_default", - }); - - const response = error.getResponse(); - expect(response.status).toBe(422); - expect(response.headers.get("content-type")).toBe( - "application/problem+json", - ); - expect(await response.json()).toEqual(json); - - const NonExposedError = createHttpErrorClass({ - name: "SecretError", - status: 500, - expose: false, - }); - const secretError = new NonExposedError("This is a secret detail", { - extensions: { secretCode: "xyz" }, - }); - const secretJson = secretError.toJSON(); - expect(secretJson).toEqual({ - status: 500, - title: "SecretError", - detail: "The server encountered an unexpected condition.", - secretCode: "xyz", - }); - expect(await secretError.getResponse().json()).toEqual(secretJson); + it("wraps any other value as a 500 caused by it", () => { + const error = HttpError.from("nope"); + expect([error.status, error.message, error.cause]).toEqual([ + 500, + "unexpected error type", + "nope", + ]); }); - it("produces classes that can be extended", () => { - const BaseError = createHttpErrorClass({ status: 409, name: "BaseError" }); - class ConflictError extends BaseError {} - const error = new ConflictError("clash"); - expect(error).toBeInstanceOf(BaseError); - expect(error).toBeInstanceOf(HttpError); - expect(error.status).toBe(409); - expect(error.toString()).toBe("BaseError: clash"); + it("keeps the reason a response could not be parsed as the cause", async () => { + const error = await HttpError.from(new Response("", { status: 502 })); + expect(error.message).toBe("could not parse problem details response"); + expect(error.cause).toBeInstanceOf(SyntaxError); }); }); describe("isHttpErrorLike", () => { - it("is true for HttpError instances", () => { - expect(isHttpErrorLike(new HttpError(400, "Bad Request"))).toBe(true); + it("is true for an HttpError", () => { + expect(isHttpErrorLike(new HttpError())).toBe(true); }); it("is true for an Error with a numeric status", () => { - const error = new Error("Bad Request"); - expect(isHttpErrorLike(error)).toBe(false); - Object.assign(error, { status: 400 }); - expect(isHttpErrorLike(error)).toBe(true); - }); - - it("is true for an Error subclass with a numeric status", () => { - class CustomHttpError extends Error { - status = 400; - } - expect(isHttpErrorLike(new CustomHttpError("bad request"))).toBe(true); - }); - - it("is false for an Error without a numeric status", () => { - expect(isHttpErrorLike(new Error("Bad Request"))).toBe(false); - expect( - isHttpErrorLike(Object.assign(new Error("x"), { status: "400" })), - ).toBe(false); + expect(isHttpErrorLike(Object.assign(new Error(), { status: 400 }))).toBe( + true, + ); }); - it.each([ - ["a plain object with a status", { status: 400, message: "Bad Request" }], - ["null", null], - ["undefined", undefined], - ["a string", "error"], - ["a number", 400], - ])("is false for %s", (_label, value) => { - expect(isHttpErrorLike(value)).toBe(false); + it("is false for an Error without a numeric status or a plain object", () => { + expect(isHttpErrorLike(Object.assign(new Error(), { status: "400" }))).toBe( + false, + ); + expect(isHttpErrorLike({ status: 400 })).toBe(false); }); }); diff --git a/typescript/src/mod.ts b/typescript/src/mod.ts index bbe0548..e67f7b6 100644 --- a/typescript/src/mod.ts +++ b/typescript/src/mod.ts @@ -1,11 +1,26 @@ -import { STATUS_CODE, STATUS_TEXT, type StatusCode } from "./status.ts"; - /** - * Default user-friendly messages for HTTP error status codes. - * These are only used when expose is false and no exposedMessage was explicitly set. + * Errors that carry an HTTP status and serialize as + * [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) Problem Details. + * + * An {@link HttpError} is data: a status, the Problem Details members (`type`, + * `title`, `detail`, `instance` and extensions), response headers, and + * whether its message is safe to show. The vectors in the repository's + * `conformance/` directory pin how that data serializes, so every language's + * package produces the same response. + * + * @example + * ```ts + * import { HttpError } from "@udibo/http-error"; + * + * const error = new HttpError({ status: 404, message: "No such user." }); + * error.toJSON(); // { status: 404, title: "Not Found", detail: "No such user." } + * ``` + * + * @module */ -const DEFAULT_EXPOSED_MESSAGES: Partial> = { - // 4xx Client Errors +import { STATUS_TEXT, type StatusCode } from "./status.ts"; + +const DEFAULT_DETAILS: Partial> = { 400: "The server cannot process the request due to a client error.", 401: "Authentication is required to access this resource.", 402: "Payment is required to access this resource.", @@ -35,7 +50,6 @@ const DEFAULT_EXPOSED_MESSAGES: Partial> = { 429: "Too many requests have been sent in a given amount of time.", 431: "The request headers are too large.", 451: "The resource is unavailable for legal reasons.", - // 5xx Server Errors 500: "The server encountered an unexpected condition.", 501: "The server does not support the functionality required.", 502: "The server received an invalid response from an upstream server.", @@ -49,447 +63,215 @@ const DEFAULT_EXPOSED_MESSAGES: Partial> = { 511: "Network authentication is required to access this resource.", }; -/** - * Gets the default exposed message for a given HTTP error status code. - * Falls back to generic client/server error messages for unknown status codes. - */ -function defaultExposedMessageForStatus(status: number): string { +const PROBLEM_DETAILS_MEMBERS: ReadonlySet = new Set([ + "type", + "status", + "title", + "detail", + "instance", +]); + +function defaultTitle(status: number): string { return ( - DEFAULT_EXPOSED_MESSAGES[status] ?? + STATUS_TEXT[status as StatusCode] ?? + (status < 500 ? "Unknown Client Error" : "Unknown Server Error") + ); +} + +function defaultDetail(status: number): string { + return ( + DEFAULT_DETAILS[status] ?? (status < 500 ? "A client error occurred." : "A server error occurred.") ); } -/** Options for initializing an HttpError. */ +function isErrorStatus(status: unknown): status is number { + return ( + typeof status === "number" && + Number.isInteger(status) && + status >= 400 && + status <= 599 + ); +} + +/** The data an {@link HttpError} is made from. Every member is optional. */ export interface HttpErrorOptions< Extensions extends object = Record, -> extends ErrorOptions { - /** The name of the error. The default value is based on error status. This will be the default value for the `title` property in the response body. */ - name?: string; - /** The message of the error. This will be the default value for the `detail` property in the response body. */ - message?: string; - /** The HTTP status associated with the error. Defaults to 500. */ +> { + /** The HTTP status, an integer from 400 to 599. Defaults to 500. */ status?: number; - /** The HTTP status text associated with the error. */ - statusText?: string; - /** - * Determines if the error detail should be exposed in the response. - * Defaults to true for client error statuses and false for server error statuses. - */ - expose?: boolean; /** - * The cause of the error. This is never exposed in the response. + * The error's internal message, for logs. It becomes the public `detail` + * only when the error is exposed and no `detail` is given. */ - cause?: unknown; + message?: string; + /** A short summary of the problem type. Defaults to the status's reason phrase. */ + title?: string; /** - * The type of the error is a URI reference that identifies the problem type. + * The explanation sent to the client. Always public when given; otherwise + * the message when exposed, else a generic sentence for the status. */ + detail?: string; + /** A URI reference that identifies the problem type. */ type?: string; - /** - * The instance of the error is a URI reference that identifies the specific occurrence of the problem. - */ + /** A URI reference that identifies this occurrence of the problem. */ instance?: string; - /** - * Additional data to send in the response. - */ + /** Extra Problem Details members. Keys named after a standard member are not serialized. */ extensions?: Extensions; - /** - * The headers to send in the response. The content-type will default to application/problem+json unless otherwise specified in the headers. - */ + /** Response headers. `content-type` defaults to `application/problem+json`. */ headers?: Headers | Record; - /** - * The message to expose in the response. This is used in toJSON() as the `detail` field. - * If not provided: - * - When expose is true and message exists, exposedMessage defaults to message - * - Otherwise, exposedMessage defaults to a generic message for the status code - * This allows you to have detailed internal error messages while showing safe, user-friendly messages to clients. - */ - exposedMessage?: string; + /** Whether the message is safe to show the client. Defaults to `true` for 4xx and `false` for 5xx. */ + expose?: boolean; + /** The error that caused this one, as on `Error`. */ + cause?: unknown; } -interface ProblemDetailsBase { +/** + * An RFC 9457 Problem Details object: the standard members plus any + * extension members. + */ +export type ProblemDetails< + Extensions extends object = Record, +> = { type?: string; status?: number; title?: string; detail?: string; instance?: string; -} - -export type ProblemDetails< - Extensions extends object = Record, -> = ProblemDetailsBase & Extensions; +} & Extensions; -function isProblemDetails>( - value: unknown, -): value is ProblemDetails { +function isProblemDetails(value: unknown): value is ProblemDetails { return ( typeof value === "object" && value !== null && - ("status" in value || "title" in value || "type" in value) + !Array.isArray(value) && + ["status", "title", "type"].some( + (member) => + (value as Record)[member] !== null && + (value as Record)[member] !== undefined, + ) ); } -/** - * Converts HttpError arguments to an options object. - * Prioritizing status and message arguments over status and message options. - * - * This function is useful for creating custom error classes that extend HttpError. - * - * ```ts - * import { - * HttpError, - * type HttpErrorOptions, - * optionsFromArgs, - * } from "@udibo/http-error"; - * - * class CustomError extends HttpError { - * constructor( - * status?: number, - * message?: string, - * options?: HttpErrorOptions, - * ); - * constructor(status?: number, options?: HttpErrorOptions); - * constructor(message?: string, options?: HttpErrorOptions); - * constructor(options?: HttpErrorOptions); - * constructor( - * statusOrMessageOrOptions?: number | string | HttpErrorOptions, - * messageOrOptions?: string | HttpErrorOptions, - * options?: HttpErrorOptions, - * ) { - * const init = optionsFromArgs( - * statusOrMessageOrOptions, - * messageOrOptions, - * options, - * ); - * super({ name: "CustomError", status: 420, ...init }); - * } - * } - * ``` - * - * @param statusOrMessageOrOptions - The status, message, or options. - * @param messageOrOptions - The message or options. - * @param options - The options. - * @returns The options object. - */ -function optionsFromArgs>( - statusOrMessageOrOptions?: number | string | HttpErrorOptions, - messageOrOptions?: string | HttpErrorOptions, - options?: HttpErrorOptions, -): HttpErrorOptions { - let status: number | undefined = undefined; - let message: string | undefined = undefined; - let init: HttpErrorOptions | undefined = options; - - if (typeof statusOrMessageOrOptions === "number") { - status = statusOrMessageOrOptions; - if (typeof messageOrOptions === "string") { - message = messageOrOptions; - } else if (messageOrOptions) { - init = messageOrOptions; - message = init?.message; - } - } else if (typeof statusOrMessageOrOptions === "string") { - message = statusOrMessageOrOptions; - init = messageOrOptions as HttpErrorOptions | undefined; - status = init?.status ?? status; - } else if (typeof messageOrOptions === "string") { - message = messageOrOptions; - } else if (!init) { - init = messageOrOptions ? messageOrOptions : statusOrMessageOrOptions; - status = init?.status ?? status; - message = init?.message; - } - - return { ...init, status, message }; -} - -/** - * Gets the human-readable name for a given HTTP error status code. - * Returns names with spaces (e.g., "Bad Request", "Not Found"). - */ -function errorNameForStatus(status: number): string { - if (STATUS_TEXT[status as StatusCode]) { - return STATUS_TEXT[status as StatusCode]; - } - return status < 500 ? "Unknown Client Error" : "Unknown Server Error"; +function stringOrUndefined(value: unknown): string | undefined { + return typeof value === "string" && value !== "" ? value : undefined; } -/** - * Checks if a name matches the old error name format for a given status. - * The old format was "{StatusText}Error" (e.g., "BadRequestError" for 400). - * This is used to convert old-format names to the new human-readable format - * when processing errors from other frameworks. - */ -function matchesOldNameFormat( - name: string | undefined, - status: number, -): boolean { - if (!name) return false; - const statusText = STATUS_TEXT[status as StatusCode]; - if (!statusText) return false; - const oldFormat = statusText.replace(/\W/g, "") + "Error"; - return name === oldFormat; +function fromProblemDetails( + problem: ProblemDetails, + fallbackStatus?: number, +): HttpError { + const { type, status, title, detail, instance, ...extensions } = problem; + return new HttpError({ + status: isErrorStatus(status) + ? status + : isErrorStatus(fallbackStatus) + ? fallbackStatus + : 500, + message: stringOrUndefined(detail), + title: stringOrUndefined(title), + type: stringOrUndefined(type), + instance: stringOrUndefined(instance), + extensions: extensions as Extensions, + }); } /** - * An error for an HTTP request. - * - * This class can be used on its own to create any HttpError. It has a few - * different call signatures you can use. The 4 examples below would throw the same - * error. - * - * ```ts - * import { HttpError } from "@udibo/http-error"; - * - * throw new HttpError(404, "file not found"); - * throw new HttpError(404, { message: "file not found" }); - * throw new HttpError("file not found", { status: 404 }); - * throw new HttpError({ status: 404, message: "file not found" }); - * ``` + * An error with an HTTP status that serializes as RFC 9457 Problem Details. * - * You can also include a cause in the optional options argument for it like you - * can with regular errors. - * - * ```ts - * import { HttpError } from "@udibo/http-error"; - * - * throw new HttpError(404, "file not found", { cause: error }); - * ``` - * - * All HttpError objects have a status associated with them. If a status is not - * provided it will default to 500. The expose property will default to true for - * client error status and false for server error status. You can override the - * default behavior by setting the expose property on the options argument. - * - * For all known HTTP error status codes, a name will be generated for them. For - * example, the name of an HttpError with the 404 status would be NotFoundError. If - * the name is not known for an HTTP error status code, it will default to - * UnknownClientError or UnknownServerError. - * - * ```ts - * import { HttpError } from "@udibo/http-error"; - * - * const error = new HttpError(404, "file not found"); - * console.log(error.toString()); // NotFoundError: file not found - * ``` - * - * If you would like to extend the HttpError class, you can pass your own error - * name in the options. - * - * ```ts - * import { HttpError, type HttpErrorOptions } from "@udibo/http-error"; - * - * class CustomError extends HttpError { - * constructor( - * message?: string, - * options?: HttpErrorOptions, - * ) { - * super(message, { name: "CustomError", status: 420, ...options }); - * } - * } - * ``` - * - * If you'd like the arguments to match the parent HttpError classes call - * signature, you can make use of the optionsFromArgs function. It will prioritize - * the status / message arguments over status / message options. - * - * ```ts - * import { - * HttpError, - * type HttpErrorOptions, - * optionsFromArgs, - * } from "@udibo/http-error"; - * - * class CustomError extends HttpError { - * constructor( - * status?: number, - * message?: string, - * options?: HttpErrorOptions, - * ); - * constructor(status?: number, options?: HttpErrorOptions); - * constructor(message?: string, options?: HttpErrorOptions); - * constructor(options?: HttpErrorOptions); - * constructor( - * statusOrMessageOrOptions?: number | string | HttpErrorOptions, - * messageOrOptions?: string | HttpErrorOptions, - * options?: HttpErrorOptions, - * ) { - * const init = optionsFromArgs( - * statusOrMessageOrOptions, - * messageOrOptions, - * options, - * ); - * super({ name: "CustomError", status: 420, ...init }); - * } - * } - * ``` - * - * The HttpError class also provides `toJSON()` and `getResponse()` methods to - * convert errors into RFC 9457 Problem Details objects or Response objects, - * respectively. This makes it easy to return standardized error responses from - * your HTTP APIs. + * Throw it from a handler and turn it into a response with + * {@link HttpError.getResponse}, or convert anything caught with + * {@link HttpError.from}. Its `name` is its `title`, so logs read + * `Not Found: No such user.`. * + * @example * ```ts * import { HttpError } from "@udibo/http-error"; * - * const error = new HttpError(403, "Access denied", { - * type: "/errors/forbidden", - * instance: "/docs/123/edit", - * extensions: { accountId: "user-abc" }, + * throw new HttpError({ + * status: 400, + * message: "Invalid input", + * type: "/errors/validation", + * extensions: { field: "email" }, * }); - * - * // Get Problem Details object - * const problemDetails = error.toJSON(); - * console.log(problemDetails); - * // Output: - * // { - * // accountId: "user-abc", - * // status: 403, - * // title: "ForbiddenError", - * // detail: "Access denied", - * // type: "/errors/forbidden", - * // instance: "/docs/123/edit" - * // } - * - * // Get a Response object - * const response = error.getResponse(); - * console.log(response.status); // 403 - * response.json().then(body => console.log(body)); // Same as problemDetails * ``` - * - * @typeparam Extensions - Other data associated with the error that will be included in the error response. - * @param status - The HTTP status associated with the error. - * @param message - The message associated with the error. - * @param options - Other data associated with the error. - * @returns An HttpError object. */ export class HttpError< Extensions extends object = Record, > extends Error { - /** - * The HTTP status associated with the error. - * Must be a client or server error status. Defaults to 500. - */ + /** The HTTP status, from 400 to 599. */ status: number; - /** The HTTP status text associated with the error. */ - statusText?: string; - /** - * Determines if the error detail should be exposed in the response. - * Defaults to true for client error statuses and false for server error statuses. - */ - expose?: boolean; - /** - * The type of the error is a URI reference that identifies the problem type. - */ + /** A short summary of the problem type. */ + title: string; + /** The explanation sent to the client; safe to render. */ + detail: string; + /** A URI reference that identifies the problem type. */ type?: string; - /** - * The instance of the error is a URI reference that identifies the specific occurrence of the problem. - */ + /** A URI reference that identifies this occurrence of the problem. */ instance?: string; - /** - * Other data associated with the error that will be included in the error response. - */ + /** Extra Problem Details members. */ extensions: Extensions; - /** - * The headers to send in the response. The content-type will default to application/problem+json unless otherwise specified in the headers. - */ + /** The response headers, including `content-type`. */ headers: Headers; + /** Whether `message` is safe to show the client. */ + expose: boolean; + /** - * The message to expose in the response. Used as the `detail` field in toJSON(). - * - If explicitly set in options, that value is used - * - If expose is true and message exists, defaults to message - * - Otherwise, defaults to a generic message for the status code + * Creates an error from its data. * - * Use this instead of `message` when rendering errors to prevent leaking internal details. + * @throws {RangeError} When `status` is not an integer from 400 to 599. */ - exposedMessage: string; - - constructor( - status?: number, - message?: string, - options?: HttpErrorOptions, - ); - constructor(status?: number, options?: HttpErrorOptions); - constructor(message?: string, options?: HttpErrorOptions); - constructor(options?: HttpErrorOptions); - constructor( - statusOrMessageOrOptions?: number | string | HttpErrorOptions, - messageOrOptions?: string | HttpErrorOptions, - options?: HttpErrorOptions, - ) { - const init = optionsFromArgs( - statusOrMessageOrOptions, - messageOrOptions, - options, - ); - const { - message, - name, - expose, - status: _status, - statusText, - cause, - type, - instance, - extensions, - headers, - exposedMessage, - } = init; - const status = init.status ?? STATUS_CODE.InternalServerError; - - if (status < 400 || status >= 600) { + constructor(options: HttpErrorOptions = {}) { + const status = options.status ?? 500; + if (!isErrorStatus(status)) { throw new RangeError("invalid error status"); } - - const errorOptions = {} as ErrorOptions; - if (typeof cause !== "undefined") errorOptions.cause = cause; - super(message, errorOptions); - + super( + options.message ?? options.detail ?? "", + "cause" in options ? { cause: options.cause } : undefined, + ); Object.defineProperty(this, "name", { configurable: true, enumerable: false, - value: name ?? errorNameForStatus(status), - writable: true, + get(this: HttpError): string { + return this.title; + }, + set(this: HttpError, name: string): void { + this.title = name; + }, }); this.status = status; - if (statusText) this.statusText = statusText; - if (type) this.type = type; - if (instance) this.instance = instance; - this.expose = expose ?? status < 500; - this.extensions = extensions ?? ({} as Extensions); - this.headers = - headers instanceof Headers ? headers : new Headers(headers ?? {}); + this.title = options.title || defaultTitle(status); + this.expose = options.expose ?? status < 500; + this.detail = + options.detail ?? + (this.expose && options.message + ? options.message + : defaultDetail(status)); + if (options.type) this.type = options.type; + if (options.instance) this.instance = options.instance; + this.extensions = options.extensions ?? ({} as Extensions); + this.headers = new Headers(options.headers); if (!this.headers.has("content-type")) { this.headers.set("content-type", "application/problem+json"); } - // Compute exposedMessage with precedence: - // 1. Explicitly provided exposedMessage option - // 2. If expose=true and message exists, use message - // 3. Default message for status code - this.exposedMessage = - exposedMessage ?? - (this.expose && this.message - ? this.message - : defaultExposedMessageForStatus(status)); } /** - * Converts any HttpError like objects into an HttpError. - * If the object is already an instance of HttpError, it will be returned as is. - * - * ```ts - * import { HttpError } from "@udibo/http-error"; + * Converts anything caught into an `HttpError`. * - * try { - * throw new Error("something went wrong"); - * } catch (cause) { - * // Converts any non HttpError objects into an HttpError before re-throwing. - * throw HttpError.from(cause); - * } - * ``` - * - * @param error - The error to convert. - * @returns An HttpError object. + * - An `HttpError` is returned as is. + * - An `Error` with a numeric `status` (such as a framework's HTTP + * exception) keeps its status, message, cause, `expose`, `title`, `type`, + * `instance` and `extensions`. Its `detail` and `headers` are not copied, + * so nothing it carries reaches the client unless it is exposed. + * - Any other `Error` becomes a 500 whose cause is that error. + * - A Problem Details object becomes the error it describes; its `detail` + * becomes the message, which is public only when the error is exposed. + * - A `Response` is parsed as Problem Details, asynchronously. A body that + * is not Problem Details gives an unexposed error with the response's + * status (500 when that is not an error status). + * - Anything else becomes a 500 whose cause is that value. */ static from>( error: HttpError | ProblemDetails, @@ -504,164 +286,94 @@ export class HttpError< static from>( error: unknown, ): HttpError | Promise> { - if (error instanceof HttpError) { - return error; - } else if (isHttpErrorLike(error)) { - const { - name: originalName, - message, + if (error instanceof HttpError) return error as HttpError; + if (isHttpErrorLike(error)) { + const status = isErrorStatus(error.status) ? error.status : 500; + const source = error as unknown as Record; + return new HttpError({ status, - expose, - cause, - type, - instance, - extensions, - headers, - exposedMessage, - } = error as HttpError; - // Use new format if name matches old format, otherwise preserve custom name - const name = matchesOldNameFormat(originalName, status) - ? undefined - : originalName; - const options = { - name, + message: error.message, + title: stringOrUndefined(source.title), + type: stringOrUndefined(source.type), + instance: stringOrUndefined(source.instance), + expose: typeof source.expose === "boolean" ? source.expose : undefined, + extensions: + typeof source.extensions === "object" && source.extensions !== null + ? (source.extensions as Extensions) + : undefined, + ...("cause" in error ? { cause: error.cause } : {}), + }); + } + if (error instanceof Error) { + return new HttpError({ + status: 500, + message: error.message, + cause: error, + }); + } + if (error instanceof Response) return HttpError.fromResponse(error); + if (isProblemDetails(error)) return fromProblemDetails(error); + return new HttpError({ + status: 500, + message: "unexpected error type", + cause: error, + }); + } + + private static async fromResponse( + response: Response, + ): Promise> { + const unparsed = (message: string, cause: unknown): HttpError => + new HttpError({ + status: isErrorStatus(response.status) ? response.status : 500, message, - status, - expose, + expose: false, cause, - type, - instance, - extensions, - exposedMessage, - headers, - } as HttpErrorOptions; - return new HttpError(options); - } else if (error instanceof Error) { - return new HttpError(500, error.message, { - cause: error, - }) as unknown as HttpError; - } else if (error instanceof Response) { - return error - .json() - .then((json: unknown) => { - if (!isProblemDetails(json)) { - return new HttpError( - 500, - "invalid problem details response", - { - cause: json, - }, - ); - } - const { status, title, detail, type, instance, ...extensions } = json; - const options: HttpErrorOptions = { - status: status || error.status, - name: title, - message: detail, - type, - instance, - extensions: extensions as Extensions, - }; - return new HttpError(options); - }) - .catch((parseError: unknown) => { - return new HttpError( - 500, - "could not parse problem details response", - { - cause: parseError, - }, - ); - }); - } else if (isProblemDetails(error)) { - const { status, title, detail, type, instance, ...extensions } = error; - const options: HttpErrorOptions = { - status, - name: title, - message: detail, - type, - instance, - extensions: extensions as Extensions, - }; - return new HttpError(options); - } else { - return new HttpError(500, "unexpected error type", { - cause: error, }); + let body: unknown; + try { + body = await response.json(); + } catch (parseError) { + return unparsed("could not parse problem details response", parseError); } + return isProblemDetails(body) + ? fromProblemDetails(body, response.status) + : unparsed("invalid problem details response", body); } - /** - * Converts the HttpError to a ProblemDetails object that matches the RFC 9457 - * Problem Details for HTTP APIs specification. This object is suitable for - * direct serialization into a JSON response body. - * - * @returns A ProblemDetails object representing the error, compliant with RFC 9457. - */ + /** The Problem Details object for this error, the JSON response body. */ toJSON(): ProblemDetails { - const json: ProblemDetails = { - ...this.extensions, - status: this.status, - title: this.name, - detail: this.exposedMessage, - }; - if (this.type) { - json.type = this.type; - } - if (this.instance) { - json.instance = this.instance; + const json: Record = {}; + if (this.type) json.type = this.type; + json.status = this.status; + json.title = this.title; + json.detail = this.detail; + if (this.instance) json.instance = this.instance; + for (const [key, value] of Object.entries(this.extensions)) { + if (!PROBLEM_DETAILS_MEMBERS.has(key)) { + Object.defineProperty(json, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); + } } - return json; + return json as ProblemDetails; } - /** - * Converts the HttpError to a Response object that matches the RFC 9457 - * Problem Details for HTTP APIs specification. The body of the response will - * be a JSON string representing the ProblemDetails object. - * - * @returns A Response object suitable for returning from an HTTP handler, compliant with RFC 9457. - */ + /** A `Response` with this error's status, headers and Problem Details body. */ getResponse(): Response { - const options: ResponseInit = { + return new Response(JSON.stringify(this.toJSON()), { status: this.status, headers: this.headers, - }; - if (this.statusText) options.statusText = this.statusText; - return new Response(JSON.stringify(this.toJSON()), options); + }); } } /** - * Checks if a value is HttpError-like (an Error with a numeric status property). - * - * This function returns true for any Error object that has a numeric `status` property, - * not just HttpError instances. This allows it to recognize HTTP errors from other - * libraries or custom error classes that follow the same pattern. - * - * If you need to verify that an error is specifically an HttpError instance - * (not just similar to one), use `error instanceof HttpError` instead. - * - * ```ts - * import { HttpError, isHttpErrorLike } from "@udibo/http-error"; - * - * let error = new Error("file not found"); - * console.log(isHttpErrorLike(error)); // false - * - * error = new HttpError(404, "file not found"); - * console.log(isHttpErrorLike(error)); // true - * console.log(error instanceof HttpError); // true - * - * // Custom error class with status property - * class CustomHttpError extends Error { - * status = 400; - * } - * const customError = new CustomHttpError("bad request"); - * console.log(isHttpErrorLike(customError)); // true - * console.log(customError instanceof HttpError); // false - * ``` - * - * @param value - The value to check. - * @returns True if the value is an HttpError or an Error with a numeric status property. + * Whether `value` is an `HttpError` or another `Error` with a numeric + * `status`, which {@link HttpError.from} keeps the status of. */ export function isHttpErrorLike< Extensions extends object = Record, @@ -669,174 +381,8 @@ export function isHttpErrorLike< value: unknown, ): value is HttpError | (Error & { status: number }) { return ( - typeof value === "object" && - value !== null && - (value instanceof HttpError || - (value instanceof Error && - typeof (value as HttpError).status === "number")) + value instanceof HttpError || + (value instanceof Error && + typeof (value as { status?: unknown }).status === "number") ); } - -/** - * Creates a new class that extends HttpError, allowing for predefined default - * options and a specific default type for extensions. - * - * This factory is useful for creating custom HttpError types tailored to specific - * kinds of errors in an application, each with its own default status, name, - * or custom extension fields. - * - * @example - * ```ts - * // Define a type for default extensions - * interface MyApiErrorExtensions { - * errorCode: string; - * requestId?: string; - * } - * - * // Create a custom error class with defaults - * const MyApiError = createHttpErrorClass({ - * name: "MyApiError", - * status: 452, // Custom default status - * extensions: { - * errorCode: "API_GENERAL_FAILURE", // Default extension value - * }, - * }); - * - * // Usage of the custom error class - * try { - * // Simulate an error condition - * throw new MyApiError("A specific API operation failed.", { - * extensions: { - * errorCode: "API_OPERATION_X_FAILED", // Override default extension - * requestId: "req-12345", // Add instance-specific extension - * }, - * }); - * } catch (e) { - * if (e instanceof MyApiError) { - * console.log(e.name); // "MyApiError" - * console.log(e.status); // 452 - * console.log(e.message); // "A specific API operation failed." - * console.log(e.extensions.errorCode); // "API_OPERATION_X_FAILED" - * console.log(e.extensions.requestId); // "req-12345" - * // console.log(e.toJSON()); - * } - * } - * - * // Example with a different status code at instantiation - * const anotherError = new MyApiError(453, "Another failure"); - * console.log(anotherError.status) // 453 - * console.log(anotherError.extensions.errorCode) // "API_GENERAL_FAILURE" - * ``` - * - * @typeparam DefaultExtensions The type for the default `extensions` object. Defaults to `Record`. - * @param defaultOptionsForClass Optional default HttpErrorOptions to apply to the new error class. - * @returns A new class that extends `HttpError`. - */ -export function createHttpErrorClass< - DefaultExtensions extends object = Record, ->( - defaultOptionsForClass?: HttpErrorOptions, -): { - new ( - status?: number, - message?: string, - options?: HttpErrorOptions, - ): HttpError; - new ( - status?: number, - options?: HttpErrorOptions, - ): HttpError; - new ( - message?: string, - options?: HttpErrorOptions, - ): HttpError; - new ( - options?: HttpErrorOptions, - ): HttpError; - prototype: HttpError; -} { - return class CustomHttpError< - Extensions extends DefaultExtensions = DefaultExtensions, - > extends HttpError { - constructor( - status?: number, - message?: string, - options?: HttpErrorOptions, - ); - constructor(status?: number, options?: HttpErrorOptions); - constructor(message?: string, options?: HttpErrorOptions); - constructor(options?: HttpErrorOptions); - constructor( - statusOrMessageOrOptions?: number | string | HttpErrorOptions, - messageOrOptions?: string | HttpErrorOptions, - optionsArgument?: HttpErrorOptions, - ) { - const constructorTimeOptions = optionsFromArgs( - statusOrMessageOrOptions, - messageOrOptions, - optionsArgument, - ); - - const dfo = defaultOptionsForClass; - - const finalOptions: HttpErrorOptions = {}; - - finalOptions.status = - constructorTimeOptions.status !== undefined - ? constructorTimeOptions.status - : dfo?.status; - - finalOptions.message = - constructorTimeOptions.message !== undefined - ? constructorTimeOptions.message - : dfo?.message; - - finalOptions.name = - constructorTimeOptions.name !== undefined - ? constructorTimeOptions.name - : dfo?.name; - - finalOptions.expose = - constructorTimeOptions.expose !== undefined - ? constructorTimeOptions.expose - : dfo?.expose; - - finalOptions.cause = - constructorTimeOptions.cause !== undefined - ? constructorTimeOptions.cause - : dfo?.cause; - - finalOptions.type = - constructorTimeOptions.type !== undefined - ? constructorTimeOptions.type - : dfo?.type; - - finalOptions.instance = - constructorTimeOptions.instance !== undefined - ? constructorTimeOptions.instance - : dfo?.instance; - - finalOptions.headers = - constructorTimeOptions.headers !== undefined - ? constructorTimeOptions.headers - : dfo?.headers; - - finalOptions.statusText = - constructorTimeOptions.statusText !== undefined - ? constructorTimeOptions.statusText - : dfo?.statusText; - - finalOptions.exposedMessage = - constructorTimeOptions.exposedMessage !== undefined - ? constructorTimeOptions.exposedMessage - : dfo?.exposedMessage; - - finalOptions.extensions = { - ...dfo?.extensions, - ...constructorTimeOptions.extensions, - } as Extensions; - - super(finalOptions); - } - }; -} diff --git a/typescript/src/status.ts b/typescript/src/status.ts index b99a413..2f50fc9 100644 --- a/typescript/src/status.ts +++ b/typescript/src/status.ts @@ -169,7 +169,7 @@ export const STATUS_TEXT = { 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", - 407: "Proxy Auth Required", + 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", @@ -182,7 +182,7 @@ export const STATUS_TEXT = { 417: "Expectation Failed", 418: "I'm a teapot", 421: "Misdirected Request", - 422: "Unprocessable Entity", + 422: "Unprocessable Content", 423: "Locked", 424: "Failed Dependency", 425: "Too Early",