From 2756f553c68082342a784ef716c62da6cea6f3ca Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 22 Feb 2019 11:46:58 +0900 Subject: Improve error handling of API (#4345) * wip * wip * wip * Update attached_notes.ts * wip * Refactor * wip * wip * wip * wip * wip * wip * wip * wip * Update call.ts * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * :v: * Fix --- src/server/api/define.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'src/server/api/define.ts') diff --git a/src/server/api/define.ts b/src/server/api/define.ts index de9a8caf96..f2fababc32 100644 --- a/src/server/api/define.ts +++ b/src/server/api/define.ts @@ -2,6 +2,7 @@ import * as fs from 'fs'; import { ILocalUser } from '../../models/user'; import { IApp } from '../../models/app'; import { IEndpointMeta } from './endpoints'; +import { ApiError } from './error'; type Params = { [P in keyof T['params']]: T['params'][P]['transform'] extends Function @@ -9,13 +10,19 @@ type Params = { : ReturnType[0]; }; -export default function (meta: T, cb: (params: Params, user: ILocalUser, app: IApp, file?: any, cleanup?: Function) => Promise): (params: any, user: ILocalUser, app: IApp, file?: any) => Promise { +export type Response = Record | void; + +export default function (meta: T, cb: (params: Params, user: ILocalUser, app: IApp, file?: any, cleanup?: Function) => Promise): (params: any, user: ILocalUser, app: IApp, file?: any) => Promise { return (params: any, user: ILocalUser, app: IApp, file?: any) => { function cleanup() { fs.unlink(file.path, () => {}); } - if (meta.requireFile && file == null) return Promise.reject('file required'); + if (meta.requireFile && file == null) return Promise.reject(new ApiError({ + message: 'File required.', + code: 'FILE_REQUIRED', + id: '4267801e-70d1-416a-b011-4ee502885d8b', + })); const [ps, pserr] = getParams(meta, params); if (pserr) { @@ -27,17 +34,22 @@ export default function (meta: T, cb: (params: Params(defs: T, params: any): [Params, Error] { +function getParams(defs: T, params: any): [Params, ApiError] { if (defs.params == null) return [params, null]; const x: any = {}; - let err: Error = null; + let err: ApiError = null; Object.entries(defs.params).some(([k, def]) => { const [v, e] = def.validator.get(params[k]); if (e) { - err = new Error(e.message); - err.name = 'INVALID_PARAM'; - (err as any).param = k; + err = new ApiError({ + message: 'Invalid param.', + code: 'INVALID_PARAM', + id: '3d81ceae-475f-4600-b2a8-2bc116157532', + }, { + param: k, + reason: e.message + }); return true; } else { if (v === undefined && def.hasOwnProperty('default')) { -- cgit v1.2.3-freya