diff options
author | Chocobozzz <me@florianbigard.com> | 2021-06-02 18:15:41 +0200 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2021-06-02 18:15:41 +0200 |
commit | e030bfb59dd5ee65f20a64686ec9b22ca39f70ae (patch) | |
tree | c9a439159ef540291e3c030bcaf958b953442147 /server/middlewares/error.ts | |
parent | 463206948d6a9d46e7e68d55c7b763e601ecc870 (diff) | |
download | PeerTube-e030bfb59dd5ee65f20a64686ec9b22ca39f70ae.tar.gz PeerTube-e030bfb59dd5ee65f20a64686ec9b22ca39f70ae.tar.zst PeerTube-e030bfb59dd5ee65f20a64686ec9b22ca39f70ae.zip |
Refactor server errors handler
Diffstat (limited to 'server/middlewares/error.ts')
-rw-r--r-- | server/middlewares/error.ts | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/server/middlewares/error.ts b/server/middlewares/error.ts new file mode 100644 index 000000000..e3eb1c8f5 --- /dev/null +++ b/server/middlewares/error.ts | |||
@@ -0,0 +1,39 @@ | |||
1 | import * as express from 'express' | ||
2 | import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details' | ||
3 | import { HttpStatusCode } from '@shared/core-utils' | ||
4 | |||
5 | function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) { | ||
6 | res.fail = options => { | ||
7 | const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance } = options | ||
8 | |||
9 | const extension = new ProblemDocumentExtension({ | ||
10 | ...data, | ||
11 | |||
12 | docs: res.locals.docUrl, | ||
13 | code: type, | ||
14 | |||
15 | // For <= 3.2 compatibility | ||
16 | error: message | ||
17 | }) | ||
18 | |||
19 | res.status(status) | ||
20 | res.setHeader('Content-Type', 'application/problem+json') | ||
21 | res.json(new ProblemDocument({ | ||
22 | status, | ||
23 | title, | ||
24 | instance, | ||
25 | |||
26 | detail: message, | ||
27 | |||
28 | type: type | ||
29 | ? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}` | ||
30 | : undefined | ||
31 | }, extension)) | ||
32 | } | ||
33 | |||
34 | if (next) next() | ||
35 | } | ||
36 | |||
37 | export { | ||
38 | apiFailMiddleware | ||
39 | } | ||