Comments (11)
npm i
npm run start:dev
- 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);
});
- And then, get request
{
"status": 0,
"message": "success",
"success": true
}
- 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.
sorry, i am not push it before.
from nest.
@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.
您能否共享引发异常的确切文件?你的复制品太大了。此外,我们需要重现问题的步骤
我会重新打开这个,你准备好了
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.
@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.
I'd like to know how to reproduce the issue just like you're doing.
Share the steps like:
npm i
npm run start:dev
curl foobar
from nest.
but there's no notification.service.ts
file in your repository
also nothing with deleteSend
from nest.
you missed a return
or await
here:
So your exception was uncaught. NestJS has nothing do deal with that. That's not a bug but the expected behavior.
from nest.
so i need to use replace then/catch
with async/await
?
from nest.
no
you can use both
please take some time to learn JS
from nest.
ok, i will, and thank you for your help.
from nest.
Related Issues (20)
- ValidationPipe({transform: true}) transforms non-numeric strings to NaN HOT 2
- Exclude version prefix for specific routes HOT 3
- If HttpAdapterHost is a provider, is it part of the current ClsModule? HOT 1
- Express Middleware not being called for some endpoints HOT 8
- Some CLI commands do not work in project root directory HOT 4
- move away from reflect-metadata HOT 1
- Typescript compilation error with fastify adapter HOT 4
- Payment integration using phonepay documentation HOT 1
- handleConnection method can conflict with WebSocket Gateway lifecycle hook HOT 1
- Feat: Add support for turbopack HOT 1
- The sequence of messages from the Observable pipe in the sse method of router-response-controller.ts is disordered. HOT 1
- configurable threshold for The module ... is taking ...ms to serialize HOT 2
- owned types are marked as extension HOT 1
- zod validation with @Param error HOT 1
- Why I can't use Logger in extended (child) classes? HOT 1
- path is undefined when using file FilesInterceptor for file uploading HOT 2
- How to use metadata to get information from decorators HOT 2
- NestJs middlewares don't run when fastify is the HTTP adapter HOT 3
- Just started with the boilerplate and test does not run HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nest.