Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何使用nestjs异常过滤器处理objectionjs上的错误?_Typescript_Nestjs_Objection.js - Fatal编程技术网

Typescript 如何使用nestjs异常过滤器处理objectionjs上的错误?

Typescript 如何使用nestjs异常过滤器处理objectionjs上的错误?,typescript,nestjs,objection.js,Typescript,Nestjs,Objection.js,我使用objective.js作为我的Nest.js应用程序的ORM。我尝试为Http异常和反对错误(ORM/数据库错误)实现全局错误处理。假设我在插入相同的唯一值时出错,它将抛出UniqueViolationError。但是每次我在应用程序的users.service.ts(用户模块服务)部分抛出错误时,在服务上错误仍然是UniqueViolationError的实例,但在过滤器上它变成了HttpExceptionError的实例,因此我的过滤器无法工作。以下是完整的代码: errors.fi

我使用objective.js作为我的Nest.js应用程序的ORM。我尝试为Http异常和反对错误(ORM/数据库错误)实现全局错误处理。假设我在插入相同的唯一值时出错,它将抛出
UniqueViolationError
。但是每次我在应用程序的
users.service.ts
(用户模块服务)部分抛出错误时,在服务上错误仍然是
UniqueViolationError
的实例,但在过滤器上它变成了
HttpExceptionError
的实例,因此我的过滤器无法工作。以下是完整的代码:

errors.filters.ts


import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  InternalServerErrorException,
} from '@nestjs/common';

import {
  ValidationError,
  NotFoundError,
  DBError,
  ConstraintViolationError,
  UniqueViolationError,
  NotNullViolationError,
  ForeignKeyViolationError,
  CheckViolationError,
  DataError,
} from 'objection';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: InternalServerErrorException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    // All the errors here are instance of HttpException, it shouldn't be :(

    if (exception instanceof ValidationError) {
      switch (exception.type) {
        case 'ModelValidation':
          response.status(HttpStatus.BAD_REQUEST).send({
            message: exception.message,
            type: exception.type,
            data: exception.data,
            timestamp: new Date().toISOString(),
            statusCode: HttpStatus.BAD_REQUEST,
            path: request.url,
          });
          break;
        case 'RelationExpression':
          response.status(HttpStatus.BAD_REQUEST).send({
            message: exception.message,
            type: 'RelationExpression',
            data: {},
            timestamp: new Date().toISOString(),
            statusCode: HttpStatus.BAD_REQUEST,
            path: request.url,
          });
          break;
        case 'UnallowedRelation':
          response.status(HttpStatus.BAD_REQUEST).send({
            message: exception.message,
            type: exception.type,
            data: {},
            timestamp: new Date().toISOString(),
            statusCode: HttpStatus.BAD_REQUEST,
            path: request.url,
          });
          break;
        case 'InvalidGraph':
          response.status(HttpStatus.BAD_REQUEST).send({
            message: exception.message,
            type: exception.type,
            data: {},
            timestamp: new Date().toISOString(),
            statusCode: HttpStatus.BAD_REQUEST,
            path: request.url,
          });
          break;
        default:
          response.status(HttpStatus.BAD_REQUEST).send({
            message: exception.message,
            type: 'UnknownValidationError',
            data: {},
            timestamp: new Date().toISOString(),
            statusCode: HttpStatus.BAD_REQUEST,
            path: request.url,
          });
          break;
      }
    } else if (exception instanceof ConstraintViolationError) {
      response.status(HttpStatus.BAD_REQUEST).json({
        statusCode: HttpStatus.BAD_REQUEST,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'ConstraintViolation',
        path: request.url,
      });
    } else if (exception instanceof DBError) {
      response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
        statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'UnknownDBError',
        path: request.url,
      });
    } else if (exception instanceof DataError) {
      response.status(HttpStatus.BAD_REQUEST).json({
        statusCode: HttpStatus.BAD_REQUEST,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'InvalidData',
        path: request.url,
      });
    } else if (exception instanceof CheckViolationError) {
      response.status(HttpStatus.BAD_REQUEST).json({
        statusCode: HttpStatus.BAD_REQUEST,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'CheckViolation',
        path: request.url,
      });
    } else if (exception instanceof ForeignKeyViolationError) {
      response.status(HttpStatus.BAD_REQUEST).json({
        statusCode: HttpStatus.BAD_REQUEST,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'ForeignKeyViolation',
        path: request.url,
      });
    } else if (exception instanceof NotNullViolationError) {
      response.status(HttpStatus.BAD_REQUEST).json({
        statusCode: HttpStatus.BAD_REQUEST,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'NotNullViolation',
        path: request.url,
      });
    } else if (exception instanceof UniqueViolationError) {
      response.status(HttpStatus.CONFLICT).json({
        statusCode: HttpStatus.CONFLICT,
        message: exception.message,
        timestamp: new Date().toISOString(),
        type: 'UniqueViolation',
        path: request.url,
      });
    } else if (exception instanceof NotFoundError) {
      response.status(HttpStatus.NOT_FOUND).json({
        statusCode: HttpStatus.NOT_FOUND,
        timestamp: new Date().toISOString(),
        message: exception.message,
        type: 'NotFound',
        path: request.url,
      });
    } else if (exception instanceof HttpException) {
      response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
        message: exception.message,
        statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
        type: 'HttpServerError',
        timestamp: new Date().toISOString(),
        path: request.url,
      });
    } else {
      response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
        type: 'UnknownErrorServer',
        statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
    }
  }
}
梅因酒店


import 'dotenv/config';

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as requestIp from 'request-ip';
import { ValidationPipe } from '@nestjs/common';
import { AllExceptionsFilter } from './filters/errors.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(requestIp.mw());
  app.enableCors();
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    }),
  );
  app.useGlobalFilters(new AllExceptionsFilter());

  // swagger documentations
  const config = new DocumentBuilder()
    .setTitle('SWAGGER')
    .setDescription('SWWAAAAG')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

  await app.listen(4040);
}
bootstrap();
users.service.ts上的函数


try {
  await this.modelQuery.query().insert({ name: 'Same name' })
} catch (error) {
  // in here still UniqueViolationError
  throm new Error(error)
}

为什么错误实例发生了更改,以及如何使其不发生更改?我做错了什么?

看起来您所有的支票都设置正确。但是现在发生的事情是,您正在创建一个新的错误对象并抛出它,而不是抛出原始的错误对象,这意味着所有的
instanceof
检查现在都是无用的,因为您抛出了一个
新错误()
。要么不捕获错误,要么捕获它并在执行日志记录或任何您需要的操作后重新抛出原始错误。

在try-catch中,错误类型为
UniqueViolationError
,这是一种
ValidationError
,对吗?我在阅读定义文件后不这么认为,
UniqueViolationError
实际上正在使用
db errors
包。在我的try catch中,错误不是
ValidationError
的实例,谢谢,事实上是这样,所以我在服务和控制器上捕获了错误。控制器以
HttpException
响应,这就是为什么它始终是
HttpException
的实例。