1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import HttpErrors from 'http-errors';
|
7 |
|
8 | export namespace RestHttpErrors {
|
9 | export function invalidData<T, Props extends object = {}>(
|
10 | data: T,
|
11 | name: string,
|
12 | extraProperties?: Props,
|
13 | ): HttpErrors.HttpError & Props {
|
14 | const msg = `Invalid data ${JSON.stringify(data)} for parameter "${name}".`;
|
15 | return Object.assign(
|
16 | new HttpErrors.BadRequest(msg),
|
17 | {
|
18 | code: 'INVALID_PARAMETER_VALUE',
|
19 | parameterName: name,
|
20 | },
|
21 | extraProperties,
|
22 | );
|
23 | }
|
24 |
|
25 | export function unsupportedMediaType(
|
26 | contentType: string,
|
27 | allowedTypes: string[] = [],
|
28 | ) {
|
29 | const msg = allowedTypes?.length
|
30 | ? `Content-type ${contentType} does not match [${allowedTypes}].`
|
31 | : `Content-type ${contentType} is not supported.`;
|
32 | return Object.assign(new HttpErrors.UnsupportedMediaType(msg), {
|
33 | code: 'UNSUPPORTED_MEDIA_TYPE',
|
34 | contentType: contentType,
|
35 | allowedMediaTypes: allowedTypes,
|
36 | });
|
37 | }
|
38 |
|
39 | export function missingRequired(name: string): HttpErrors.HttpError {
|
40 | const msg = `Required parameter ${name} is missing!`;
|
41 | return Object.assign(new HttpErrors.BadRequest(msg), {
|
42 | code: 'MISSING_REQUIRED_PARAMETER',
|
43 | parameterName: name,
|
44 | });
|
45 | }
|
46 |
|
47 | export function invalidParamLocation(location: string): HttpErrors.HttpError {
|
48 | const msg = `Parameters with "in: ${location}" are not supported yet.`;
|
49 | return new HttpErrors.NotImplemented(msg);
|
50 | }
|
51 |
|
52 | export const INVALID_REQUEST_BODY_MESSAGE =
|
53 | 'The request body is invalid. See error object `details` property for more info.';
|
54 |
|
55 | export function invalidRequestBody(
|
56 | details: ValidationErrorDetails[],
|
57 | ): HttpErrors.HttpError & {details: ValidationErrorDetails[]} {
|
58 | return Object.assign(
|
59 | new HttpErrors.UnprocessableEntity(INVALID_REQUEST_BODY_MESSAGE),
|
60 | {
|
61 | code: 'VALIDATION_FAILED',
|
62 | details,
|
63 | },
|
64 | );
|
65 | }
|
66 |
|
67 | |
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | export interface ValidationErrorDetails {
|
74 | |
75 |
|
76 |
|
77 | path: string;
|
78 | |
79 |
|
80 |
|
81 | code: string;
|
82 | |
83 |
|
84 |
|
85 | message: string;
|
86 | |
87 |
|
88 |
|
89 | info: object;
|
90 | }
|
91 | }
|