Как вернуть исключение из общего обработчика ошибок в nodejs - PullRequest
0 голосов
/ 26 марта 2020

Мой API в nodejs с многоуровневой архитектурой. Я сталкиваюсь с проблемой возвращения ошибки из любого места в приложении. Мой обработчик ошибок express фиксирует ошибку, но затем выполняется логика моего контроллера c. Ниже приведен пример кода.

//accountcontroller.ts

updateAccountStatus = async (req: Request, res: Response, next: any): Promise<any> => {
    let responseFromService = await AccountService.updateAccountStatus(
        parseInt(req.params.accountId),
        next
    );

    // even after the exception it comes here, after visiting the express default error code
    if (responseFromService !== undefined) {
        responseHandler(res, 200, responseFromService);
    }

    if (responseFromService.err) {
       return next(responseFromService);
    }


//accountService.ts

  public updateAccountStatus = async (accountId: number, next: any): Promise<any> => {
    let accountStatusReponse = await accountRepository.updateAccountStatus(accountId, next);

    return accountStatusReponse;
  };

//accountRepository.ts

public updateAccountStatus = async (accountId: any, next: any): Promise<any> => {
        try {

        const updateAccountStatus = await Accounts.updateOne(
          { id: accountId },
          { accountStatus: true }
        );
        if (updateAccountStatus) {
          return updateAccountStatus;
        } else {
          throw new Error("Error while saving the data");
        }

    } catch (error) {
      error.err = error.message;
      error.status = 500;
      return next(error);
    }
  };

// responseHandler - это мой файл общего доступа для возврата ответов.

responseHandler.ts

class responseHandler {
  constructor() {}
  statusCodeResponse = (
    response: any,
    message: string,
    statusCode: number,
  ): void => {
    response.statusMessage = statusMessage;
    response
      .status(statusCode)
      .json(
        response: response,
        message: message
        )
      );
  };
}

// app. js

import accountRouter from "./routes/accountroute";

var app = express();
app.use("/accounts", accountRouter);

Любые предложения о том, как сделать возврат, чтобы в случае исключения элемент управления не возвращался к предыдущему файлу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...