Skip to content

Commit 9c10d76

Browse files
committed
enable using method for server errors
1 parent 9ce9b2f commit 9c10d76

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
@@ -48,7 +48,7 @@ class Server {
4848
}
4949
catch (e) {
5050
if (e instanceof Request.BadUrlError) {
51-
this.errors._get(ServerErrorRegistry.ErrorCodes.BAD_URL)._send(res, this);
51+
this.errors._get(ServerErrorRegistry.ErrorCodes.BAD_URL, null)._send(res, this);
5252
return;
5353
}
5454
if (e instanceof Request.SocketClosedError)
@@ -70,10 +70,10 @@ class Server {
7070
}
7171
catch (e) {
7272
if (e instanceof RouteRegistry.NoRouteError)
73-
response = this.errors._get(ServerErrorRegistry.ErrorCodes.NO_ROUTE);
73+
response = this.errors._get(ServerErrorRegistry.ErrorCodes.NO_ROUTE, apiRequest);
7474
else {
7575
console.error("Internal Server Error:", e);
76-
response = this.errors._get(ServerErrorRegistry.ErrorCodes.INTERNAL);
76+
response = this.errors._get(ServerErrorRegistry.ErrorCodes.INTERNAL, apiRequest);
7777
}
7878
}
7979
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)