简体   繁体   中英

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".

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). 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:

{
  "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. 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. With this approach, Nest will recognise your exceptions, and automatically take care of the error responses. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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