简体   繁体   English

如何从回调返回 json 消息而不是触发错误 | NestJs 文件上传

[英]How to return json message from callback instead of triggering error | NestJs File upload

I am working on Nestjs Multer File Upload, I have created a file filter for FileInterceptor, I wanna send a response back instead of sending an error, I have to send a JSON with the message as "file type is not supported".我正在处理 Nestjs Multer 文件上传,我为 FileInterceptor 创建了一个文件过滤器,我想发回响应而不是发送错误,我必须发送一个带有“不支持文件类型”消息的 JSON。

export const FileFilter = (req, file, callback) => {
 if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
   return callback(new Error('Only image files supported!'), false);
 }
 callback(null, true);
}

Instead of sending new Error(), I would like to send而不是发送新的错误(),我想发送

res.send({status:"error",message:"File types does not supported"});

This action is performed by a built-in global exception filter, which handles exceptions of type HttpException (and subclasses of it).此操作由内置的全局异常过滤器执行,该过滤器处理 HttpException 类型的异常(及其子类)。 When an exception is unrecognised (is neither HttpException nor a class that inherits from HttpException), the built-in exception filter generates the following default JSON response:当无法识别异常(既不是 HttpException 也不是继承自 HttpException 的类)时,内置异常过滤器会生成以下默认 JSON 响应:

{
  "statusCode": 500,
  "message": "Internal server error"
}

In many cases, you will not need to write custom exceptions, and can use the built-in Nest HTTP exception, as described in the next section.在许多情况下,您不需要编写自定义异常,并且可以使用内置的 Nest HTTP 异常,如下一节所述。 If you do need to create customised exceptions, it's good practice to create your own exceptions hierarchy, where your custom exceptions inherit from the base HttpException class.如果确实需要创建自定义异常,最好创建自己的异常层次结构,其中自定义异常继承自 HttpException 基类。 With this approach, Nest will recognise your exceptions, and automatically take care of the error responses.通过这种方法,Nest 将识别您的异常,并自动处理错误响应。 Let's implement such a custom exception:让我们实现这样一个自定义异常:

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

@Catch()
export class ErrorFilter implements ExceptionFilter {
  catch(error: Error, host: ArgumentsHost) {
    let response = host.switchToHttp().getResponse();
    let status = (error instanceof HttpException) ? error.message: HttpStatus.INTERNAL_SERVER_ERROR;
    if (status.statusCode === HttpStatus.BAD_REQUEST) {
        return response.status(HttpStatus.BAD_REQUEST).send(status)
    }

    if (status.statusCode === HttpStatus.NOT_FOUND) {
        return response.status(HttpStatus.NOT_FOUND).send(status)
    }
 
    if (status.statusCode === HttpStatus.UNAUTHORIZED) 
        return response.status(status.statusCode).send(status)

        
    if (status.statusCode === HttpStatus.NOT_FOUND) 
        return response.status(status).send(status)
    if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
        if (process.env.NODE_ENV === 'production') {
          console.error(error.stack);
          return response.status(status).render('views/500');
        }
        else {
          let message = error.stack;
          return response.status(status).send(message); 
        } 
    }

  }
}

For more details, you can check the Nest.js documentation custom exception filter.有关更多详细信息,您可以查看Nest.js文档自定义异常过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM