Node.js 使用FileInterceptor上载文件时,如何在NestJs中返回自定义状态代码?

Node.js 使用FileInterceptor上载文件时,如何在NestJs中返回自定义状态代码?,node.js,nestjs,Node.js,Nestjs,我正在尝试为不同类型的异常返回自定义状态代码。虽然我正确地接收到了响应,但我无法在不引起错误的情况下完成它。只有在条件块中(如果我在post请求中发送文件),错误才会发生。else块中没有错误 错误:检测到循环依赖关系 // Below code gives this error => Error: cyclic dependency detected import { Controller, Post, Req, Res, UseInterceptors, UploadedFile

我正在尝试为不同类型的异常返回自定义状态代码。虽然我正确地接收到了响应,但我无法在不引起错误的情况下完成它。只有在条件块中(如果我在post请求中发送文件),错误才会发生。else块中没有错误

错误:检测到循环依赖关系

// Below code gives this error =>  Error: cyclic dependency detected

import { Controller, Post, Req, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request, Response } from 'express';

@Controller('testing')
export class TestController {
    constructor() { }

    @Post('/upload')
    @UseInterceptors(FileInterceptor('file'))
    upload(@UploadedFile() file, @Res() response: Response) { 
        if (file && file !== undefined) {
            return response.status(200).json({
                status: "OK",
                message: "File Uploaded"
            });
        } else {
            return response.status(400).json({
                status: "BAD REQUEST",
                message: "File not found"
            });
        }
    }
}

我刚才也犯了类似的错误

如果确实要使用
@Res
,请尝试将其与
passthrough
参数一起使用

类似这样的东西(我做了一些重构使它更干净)

p、 并尝试使用
HttpStatus
enum来保持代码的可读性

但有一个更好、更干净的解决方案。如果文件不在那里,您只需抛出一个带有所需消息的
BadRequestException
,NestJS将神奇地为您处理一切=D

    @Post("/upload")
    @HttpCode(HttpStatus.OK)
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file) {
        if (!file) {
            throw new BadRequestException("File not found!");
        }
        // do something with the file...
    }

我刚才也犯了类似的错误

如果确实要使用
@Res
,请尝试将其与
passthrough
参数一起使用

类似这样的东西(我做了一些重构使它更干净)

p、 并尝试使用
HttpStatus
enum来保持代码的可读性

但有一个更好、更干净的解决方案。如果文件不在那里,您只需抛出一个带有所需消息的
BadRequestException
,NestJS将神奇地为您处理一切=D

    @Post("/upload")
    @HttpCode(HttpStatus.OK)
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file) {
        if (!file) {
            throw new BadRequestException("File not found!");
        }
        // do something with the file...
    }

您可以添加您在终端中收到的完整错误吗?您可以添加您在终端中收到的完整错误吗?