Repository navigation
Expand file tree
/
Copy pathproblem-details.ts
More file actions
61 lines (55 loc) · 1.9 KB
/
Copy pathproblem-details.ts
File metadata and controls
61 lines (55 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import type {
FieldError,
ValidationError,
} from "../shared/validation.error.js";
import type { UserError } from "../users/user.error.js";
import type { HttpError } from "./http.error.js";
// Every error that can leave the API.
export type AnyError = HttpError | ValidationError | UserError;
// RFC 9457 Problem Details, plus three extension members.
export type ProblemDetails = {
readonly type: "about:blank";
readonly title: string;
readonly status: number;
readonly detail: string;
readonly instance: string;
readonly code: string;
readonly requestId: string;
readonly errors?: readonly FieldError[];
};
export type ProblemContext = {
readonly instance: string;
readonly requestId: string;
};
// A Record over every error code: a code added to an error type does not
// compile until it has a status here. No other code names an error status.
const RESPONSE_BY_CODE: Record<
AnyError["code"],
{ readonly status: number; readonly title: string }
> = {
"Http.malformedJson": { status: 400, title: "Bad Request" },
"Http.routeNotFound": { status: 404, title: "Not Found" },
"Http.unexpected": { status: 500, title: "Internal Server Error" },
"Validation.invalidBody": { status: 422, title: "Unprocessable Content" },
"User.emailTaken": { status: 409, title: "Conflict" },
"User.notFound": { status: 404, title: "Not Found" },
"User.invalidEmail": { status: 422, title: "Unprocessable Content" },
"User.invalidName": { status: 422, title: "Unprocessable Content" },
};
// The one translation from an error to a response.
export function toProblem(
error: AnyError,
{ instance, requestId }: ProblemContext,
): ProblemDetails {
const { status, title } = RESPONSE_BY_CODE[error.code];
return {
type: "about:blank",
title,
status,
detail: error.detail,
instance,
code: error.code,
requestId,
...("errors" in error ? { errors: error.errors } : {}),
};
}