-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem.ts
55 lines (52 loc) · 1.27 KB
/
problem.ts
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
import { sanitize } from "../utils"
/**
* @typedef {object} ProblemInit
* @property {string} [type]
* @property {string} title
* @property {number} [status] Default: 500
* @property {string} details
*/
export type ProblemInit = Pick<Problem, "type" | "title" | "status" | "detail">
/**
* A customizable error. Used to generate a Problem Details response.
* @extends {Error}
* @constructor
* @param {ProblemInit} init
* @see https://datatracker.ietf.org/doc/html/rfc7807
*/
export class Problem extends Error {
title: string
detail: string
type?: string
status?: number
response: Response
constructor(init: ProblemInit) {
super()
// Error
this.name = init.title.replace(/\s/g, "")
this.message = init.detail
// Problem Details
this.type = init.type
this.title = init.title
this.status = init.status ?? 500
this.detail = init.detail
// response
this.response = new Response(
JSON.stringify(
sanitize({
detail: this.detail,
status: this.status,
title: this.title,
type: this.type,
}),
),
{
status: this.status,
statusText: "Problem Details",
headers: {
"Content-Type": "application/json",
},
},
)
}
}