Skip to content

Commit 535f57d

Browse files
authored
Enable using method for server errors (#23)
2 parents 1bce907 + bd8e2c9 commit 535f57d

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

src/Server.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ class Server {
5252
}
5353
catch (e) {
5454
if (e instanceof Request.BadUrlError) {
55-
this.errors._get(ServerErrorRegistry.ErrorCodes.BAD_URL)._send(res, this);
55+
this.errors._get(ServerErrorRegistry.ErrorCodes.BAD_URL, null)._send(res, this);
5656
return;
5757
}
5858
if (e instanceof Request.SocketClosedError)
@@ -74,10 +74,10 @@ class Server {
7474
}
7575
catch (e) {
7676
if (e instanceof RouteRegistry.NoRouteError)
77-
response = this.errors._get(ServerErrorRegistry.ErrorCodes.NO_ROUTE);
77+
response = this.errors._get(ServerErrorRegistry.ErrorCodes.NO_ROUTE, apiRequest);
7878
else {
7979
console.error("Internal Server Error:", e);
80-
response = this.errors._get(ServerErrorRegistry.ErrorCodes.INTERNAL);
80+
response = this.errors._get(ServerErrorRegistry.ErrorCodes.INTERNAL, apiRequest);
8181
}
8282
}
8383
response._send(res, this, apiRequest);

src/ServerErrorRegistry.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import {Response} from "./response/Response.js";
2+
import {Request} from "./Request.js";
23
import {TextResponse} from "./response/TextResponse.js";
34

45
/**
56
* A registry for server errors.
67
*/
78
class ServerErrorRegistry {
8-
private readonly responses: Record<ServerErrorRegistry.ErrorCodes, Response>;
9+
private readonly responses: Record<ServerErrorRegistry.ErrorCodes, Response | ((req?: Request) => Response)>;
910

1011
/**
1112
* Create a new server error registry initialised with default responses.
@@ -28,13 +29,15 @@ class ServerErrorRegistry {
2829
* @param code The server error code.
2930
* @param response The response to send.
3031
*/
31-
public register(code: ServerErrorRegistry.ErrorCodes, response: Response) {
32+
public register(code: ServerErrorRegistry.ErrorCodes, response: Response | ((req?: Request) => Response)) {
3233
this.responses[code] = response;
3334
}
3435

3536
/** @internal */
36-
public _get(code: ServerErrorRegistry.ErrorCodes): Response {
37-
return this.responses[code];
37+
public _get(code: ServerErrorRegistry.ErrorCodes, req: Request | null): Response {
38+
const r = this.responses[code];
39+
if (typeof r === "function") return r(req ?? void 0);
40+
return r;
3841
}
3942
}
4043

0 commit comments

Comments
 (0)