Coder Social home page Coder Social logo

Comments (11)

JulienZeng avatar JulienZeng commented on June 17, 2024 1
  1. npm i
  2. npm run start:dev
  3. Accessing an endpoint, such as...
// use axios
var axios = require('axios');
var qs = require('qs');
var data = qs.stringify({
   'notificationID': 'Notification-00009' 
});
var config = {
   method: 'post',
   url: 'http://localhost:3000/cms/notification/deleteSend',
   headers: { 
      'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJVQ1MtMDAwMDEiLCJ1c2VyUm9sZSI6NiwiaWF0IjoxNzE1Mzc5MjIxLCJleHAiOjE3MTU0MDgwMjF9.2lgcdo0t8tA-IkHZ44xp5htoD7ZTUUTxeLEHfnAKp68', 
      'User-Agent': 'Apifox/1.0.0 (https://apifox.com)', 
      'Accept': '*/*', 
      'Host': 'localhost:3000', 
      'Connection': 'keep-alive', 
      'Content-Type': 'application/x-www-form-urlencoded'
   },
   data : data
};

axios(config)
.then(function (response) {
   console.log(JSON.stringify(response.data));
})
.catch(function (error) {
   console.log(error);
});
  1. And then, get request
{
    "status": 0,
    "message": "success",
    "success": true
}
  1. But nest crashes
[Nest] 34204  - 2024/05/11 06:14:24     LOG [NestApplication] Nest application successfully started +5ms
2
BusinessException: 通知不存在。
    at F:\Program\ClubManagementSys\club-admin\src\system\notification\notification.service.ts:238:15
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

from nest.

JulienZeng avatar JulienZeng commented on June 17, 2024 1

sorry, i am not push it before.

from nest.

micalevisk avatar micalevisk commented on June 17, 2024

@JulienZeng can you share the exact file where's the exception is being raised? your repro is too big. Also, we need the steps to reproduce the issue

I'll reopen this you're ready

from nest.

JulienZeng avatar JulienZeng commented on June 17, 2024

您能否共享引发异常的确切文件?你的复制品太大了。此外,我们需要重现问题的步骤

我会重新打开这个,你准备好了

When I use throw new BusinessException,
console

BusinessException: 通知不存在。
    at F:\Program\ClubManagementSys\club-admin\src\system\notification\notification.service.ts:238:15
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

And then crash.

This is how i use it

        throw new BusinessException({
          code: BUSINESS_ERROR_CODE.NO_EXIST,
          message: '通知不存在。',
        });

Actually, it crashes everywhere I use that method.

from nest.

JulienZeng avatar JulienZeng commented on June 17, 2024

@micalevisk
base.exception.filter.ts

// 处理统一异常
import { Request, Response } from 'express';
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpStatus,
  ServiceUnavailableException,
} from '@nestjs/common';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    // 非 HTTP 标准异常处理。
    response.status(HttpStatus.SERVICE_UNAVAILABLE).json({
      statusCode: HttpStatus.SERVICE_UNAVAILABLE,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: new ServiceUnavailableException().getResponse(),
    });
  }
}

business.exception.ts

// 处理业务运行中预知且主动抛出的异常
import { HttpException, HttpStatus } from '@nestjs/common';
import { BUSINESS_ERROR_CODE } from '../constants/business.error.codes.constants';

type BusinessError = {
  code: number;
  message: string;
};
export class BusinessException extends HttpException {
  constructor(err: BusinessError | string) {
    if (typeof err === 'string') {
      err = {
        code: BUSINESS_ERROR_CODE.COMMON,
        message: err,
      };
    }
    super(err, HttpStatus.OK);
  }

  static throwForbidden() {
    throw new BusinessException({
      code: BUSINESS_ERROR_CODE.ACCESS_FORBIDDEN,
      message: '无此权限!',
    });
  }
}

http.exception.filter.ts

// 处理HTTP类型的接口相关异常
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { BusinessException } from './business.exception';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    // 处理业务异常
    if (exception instanceof BusinessException) {
      const error = exception.getResponse();
      response.status(HttpStatus.OK).send({
        data: null,
        status: error['code'],
        message: error['message'],
        success: false,
      });
      return;
    }

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception.getResponse(),
    });
  }
}

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './common/interceptor/transform.interceptor';
import { ValidationPipe } from '@nestjs/common';
import { AllExceptionsFilter } from './common/exceptions/base.exception.filter';
import { HttpExceptionFilter } from './common/exceptions/http.exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 全局路由前缀
  app.setGlobalPrefix('cms');
  // 统一响应体格式
  app.useGlobalInterceptors(new TransformInterceptor());
  // 自动验证请求参数
  app.useGlobalPipes(new ValidationPipe());
  // 全局异常过滤器
  app.useGlobalFilters(new AllExceptionsFilter(), new HttpExceptionFilter());

  app.enableCors();
  await app.listen(3000);
}
bootstrap();

``

from nest.

micalevisk avatar micalevisk commented on June 17, 2024

I'd like to know how to reproduce the issue just like you're doing.

Share the steps like:

  1. npm i
  2. npm run start:dev
  3. curl foobar

from nest.

micalevisk avatar micalevisk commented on June 17, 2024

but there's no notification.service.ts file in your repository

also nothing with deleteSend

image

from nest.

micalevisk avatar micalevisk commented on June 17, 2024

you missed a return or await here:

image

So your exception was uncaught. NestJS has nothing do deal with that. That's not a bug but the expected behavior.

from nest.

JulienZeng avatar JulienZeng commented on June 17, 2024

so i need to use replace then/catch with async/await?

from nest.

micalevisk avatar micalevisk commented on June 17, 2024

no

you can use both

please take some time to learn JS

from nest.

JulienZeng avatar JulienZeng commented on June 17, 2024

ok, i will, and thank you for your help.

from nest.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.