hakumizuki 4 лет назад
Родитель
Сommit
b02b465cf7

+ 0 - 12
packages/slack/src/interfaces/http-errors.ts

@@ -1,12 +0,0 @@
-import { HttpError } from 'http-errors';
-
-export class CustomHttpError extends Error {
-
-  httpError: HttpError
-
-  constructor(httpError: HttpError) {
-    super(httpError.message);
-    this.httpError = httpError;
-  }
-
-}

+ 3 - 3
packages/slack/src/middlewares/verify-slack-request.ts

@@ -18,7 +18,7 @@ export const verifySlackRequest = (req: RequestFromSlack, res: Response, next: N
   if (signingSecret == null) {
     const message = 'No signing secret.';
     logger.warn(message, { body: req.body });
-    throw createError(400, message);
+    return next(createError(400, message));
   }
 
   // take out slackSignature and timestamp from header
@@ -35,7 +35,7 @@ export const verifySlackRequest = (req: RequestFromSlack, res: Response, next: N
   const time = Math.floor(new Date().getTime() / 1000);
   if (Math.abs(time - timestamp) > 300) {
     const message = 'Verification failed.';
-    logger.warn(message, { body: req.body, errTYPE: createError(403, message).status });
+    logger.warn(message, { body: req.body });
     return next(createError(403, message));
   }
 
@@ -53,5 +53,5 @@ export const verifySlackRequest = (req: RequestFromSlack, res: Response, next: N
 
   const message = 'Verification fail';
   logger.warn(message, { body: req.body });
-  throw createError(403, message);
+  return next(createError(403, message));
 };

+ 6 - 1
packages/slackbot-proxy/src/Server.ts

@@ -18,7 +18,8 @@ import { createTerminus } from '@godaddy/terminus';
 
 import swaggerSettingsForDev from '~/config/swagger/config.dev';
 import swaggerSettingsForProd from '~/config/swagger/config.prod';
-import './filters/HttpErrorsFilter';
+import { GlobalHttpErrorHandlingMiddleware } from './middlewares/GlobalHttpErrorHandlingMiddleware';
+import './filters/CustomHttpErrorFilter';
 import './filters/ResourceNotFoundFilter';
 import loggerFactory from '~/utils/logger';
 
@@ -147,6 +148,10 @@ export class Server {
     this.setupLogger();
   }
 
+  $afterRoutesInit(): void {
+    this.app.use(GlobalHttpErrorHandlingMiddleware);
+  }
+
   $beforeListen(): void {
     const expressApp = this.app.getApp();
     const server = this.injector.get<HttpServer>(HttpServer);

+ 9 - 8
packages/slackbot-proxy/src/controllers/growi-to-slack.ts

@@ -2,6 +2,7 @@ import {
   Controller, Get, Post, Inject, Req, Res, UseBefore, PathParams,
 } from '@tsed/common';
 import axios from 'axios';
+import createError from 'http-errors';
 
 import { WebAPICallOptions, WebAPICallResult } from '@slack/web-api';
 
@@ -89,7 +90,7 @@ export class GrowiToSlackCtrl {
     const { tokenGtoPs } = req;
 
     if (tokenGtoPs.length !== 1) {
-      return res.status(400).send({ message: 'installation is invalid' });
+      throw createError(400, 'installation is invalid');
     }
 
     const tokenGtoP = tokenGtoPs[0];
@@ -106,7 +107,7 @@ export class GrowiToSlackCtrl {
 
       const token = relation.installation.data.bot?.token;
       if (token == null) {
-        return res.status(400).send({ message: 'installation is invalid' });
+        throw createError(400, 'installation is invalid');
       }
 
       try {
@@ -114,12 +115,12 @@ export class GrowiToSlackCtrl {
       }
       catch (err) {
         logger.error(err);
-        return res.status(400).send({ message: `failed to request to GROWI. err: ${err.message}` });
+        throw createError(400, `failed to request to GROWI. err: ${err.message}`);
       }
 
       const status = await getConnectionStatus(token);
       if (status.error != null) {
-        return res.status(400).send({ message: `failed to get connection. err: ${status.error}` });
+        throw createError(400, `failed to get connection. err: ${status.error}`);
       }
 
       return res.send({ relation, slackBotToken: token });
@@ -133,7 +134,7 @@ export class GrowiToSlackCtrl {
       .getOne();
 
     if (order == null || order.isExpired()) {
-      return res.status(400).send({ message: 'order has expired or does not exist.' });
+      throw createError(400, 'order has expired or does not exist.');
     }
 
     // Access the GROWI URL saved in the Order record and check if the GtoP token is valid.
@@ -142,19 +143,19 @@ export class GrowiToSlackCtrl {
     }
     catch (err) {
       logger.error(err);
-      return res.status(400).send({ message: `failed to request to GROWI. err: ${err.message}` });
+      throw createError(400, `failed to request to GROWI. err: ${err.message}`);
     }
 
     logger.debug('order found', order);
 
     const token = order.installation.data.bot?.token;
     if (token == null) {
-      return res.status(400).send({ message: 'installation is invalid' });
+      throw createError(400, 'installation is invalid');
     }
 
     const status = await getConnectionStatus(token);
     if (status.error != null) {
-      return res.status(400).send({ message: `failed to get connection. err: ${status.error}` });
+      throw createError(400, `failed to get connection. err: ${status.error}`);
     }
 
     logger.debug('relation test is success', order);

+ 22 - 0
packages/slackbot-proxy/src/filters/CustomHttpErrorFilter.ts

@@ -0,0 +1,22 @@
+import {
+  Catch, ExceptionFilterMethods, PlatformContext, PlatformResponse,
+} from '@tsed/common';
+
+import { CustomHttpError } from '~/models/errors';
+
+@Catch(CustomHttpError)
+export class CustomHttpErrorFilter implements ExceptionFilterMethods {
+
+  async catch(exception: CustomHttpError, ctx: PlatformContext): Promise<PlatformResponse<any>> {
+    const { httpError } = exception;
+    const { response } = ctx;
+
+    return response
+      .status(httpError.status)
+      .body({
+        status: httpError.status,
+        message: httpError.message,
+      });
+  }
+
+}

+ 0 - 20
packages/slackbot-proxy/src/filters/HttpErrorsFilter.ts

@@ -1,20 +0,0 @@
-import {
-  Catch, ExceptionFilterMethods, PlatformContext, PlatformResponse,
-} from '@tsed/common';
-import { CustomHttpError } from '@growi/slack';
-
-@Catch(CustomHttpError)
-export class HttpErrorsFilter implements ExceptionFilterMethods {
-
-  catch(exception: CustomHttpError, ctx: PlatformContext): PlatformResponse<any> {
-    // status が欲しい
-    console.log('CATCHEDDDDD!!!!!!');
-    const { response } = ctx;
-
-    console.log('$$$EXC$$$');
-    console.log(exception.message);
-
-    return response.status(418).body(exception.message);
-  }
-
-}

+ 13 - 0
packages/slackbot-proxy/src/models/errors.ts

@@ -1,5 +1,7 @@
 import ExtensibleCustomError from 'extensible-custom-error';
 
+import { HttpError } from 'http-errors';
+
 export class InvalidUrlError extends ExtensibleCustomError {
 
   constructor(url: string) {
@@ -7,3 +9,14 @@ export class InvalidUrlError extends ExtensibleCustomError {
   }
 
 }
+
+export class CustomHttpError extends Error {
+
+  httpError: HttpError
+
+  constructor(httpError: HttpError) {
+    super(httpError.message);
+    this.httpError = httpError;
+  }
+
+}