捕获自定义错误并发回自定义响应

我经常遇到这个问题,我从middlewaresservices抛出了一个自定义错误。 我想捕获此自定义错误,并发送回格式正确的响应,如下所示。

{
  "error" : {
         "status":422,"message": "Please upload a jpeg or png file!"
    }
 }

中间件


const multer = require('multer')
const aws = require('aws-sdk');
const multerS3 = require('multer-s3');
const config = require('config')


aws.config.update({
    secretaccessKey: config.get("aws_secret_access"),accessKeyId: config.get("aws_access_key")
  });

const s3 = new aws.S3()


//accept only jpeg and png files
const fileFilter = (req,file,cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null,true)
    } else {
        cb(new Error('Invalid Mime Type,only JPEG and PNG'),false);
    }
  }

const upload = multer({
    fileFilter,limits: {
        fileSize: 1024 * 1024 *5
    },storage: multerS3({
      s3:s3,bucket: config.get("bucket"),acl: 'public-read',filename: function (req,cb) {
        cb(null,Date.now().toString())
      }
    })
  })

module.exports  = upload

路由器

router.post('/personal-detail',verify,upload.single('image'),async (req,res) => {

    if(req.fileValidationError) {
        return res.end(req.fileValidationError);
  }
    //validate data before creating user
    const { error } = validatePersonalDetail(req.body)
    if (error) return res.status(400).send({ error: { status: 400,message: error.details[0].message } })
    //create user
    try {
        const user = await User.findOne({ where: { id: req.user.id } })
        if (!user) {
            return res.status(400).send({ error: { status: 400,message: "User not found. Pleae register." } })
        } else {
            const personal_detail = await fillPersonalDetail(req,res)
            const result = _.omit(personal_detail,['id'])
            return res.status(201).send(result)
        }
    } catch (err) {
        console.log(err)
        return res.status(500).send({ error: { status: 500,message: "Something went wrong." } })
    }
})

我想捕获无效的mimetype错误。
我也有一个错误的中间件。

//Handle any error
app.use(function(err,req,res,next) {
    // Do logging and user-friendly error message display
    logger.log({
      level:'error',message:err.message
    })
    console.log(err)
    res.status(500).send({error:{status:500,message: 'Something went wrong!'}}); 
})

我要修改的中间件的方式是,如果它是自定义错误,则它应按照定义发送消息,否则响应为“发生错误”。

类似下面的内容。

//Handle any error
app.use(function(err,next) {

    if(err typeOfCustomError) {
        return res.status(err.status).send(err.message)
     }
    // Do logging and user-friendly error message display
    logger.log({
      level:'error',message: 'Something went wrong!'}}); 
})
hellobaby12321 回答:捕获自定义错误并发回自定义响应

我找到了一种方法来实现它。我创建了一个扩展total=sum(items[1] for items in table) 的{​​{1}}。

customError

在我的中间件软件中,我只是检查错误的类型。

Error

简单!
这种方法的缺点是我必须在任何地方都'use strict' class CustomError extends Error { constructor(message = 'Something went wrong!',status) { super(message) this.name = 'CustomError'; // Custom debugging information this.message = message; this.status = status; } } module.exports = CustomError ,如果有人有解决方案,请发表评论。

,

如果您将使用next(),它将在您的中间件中切换,那么您可以从那里传递所有自定义消息。

<p>Resize this frame to see the responsive effect!</p>

<div class="row">
  <!-- First Column -->
  <div class="column" style="background-color: #dc3545;">
    <h2>Column 1</h2>
    <p>Some Text...</p>
    <p>Some Text...</p>
    <p>Some Text...</p>
  </div>
  <!-- Second Column -->
  <div class="column" style="background-color: #ffc107;">
    <h2>Column 2</h2>
    <p>Some Text...</p>
    <p>Some Text...</p>
    <p>Some Text...</p>    
  </div>
  <!-- Third Column -->
  <div class="column" style="background-color: #007eff;">
    <h2>Column 3</h2>
    <p>Some Text...</p>
    <p>Some Text...</p>
    <p>Some Text...</p>    
  </div>
  <!-- Fourth Column -->
  <div class="column" style="background-color: #28a745;">
    <h2>Column 4</h2>
    <p>Some Text...</p>
    <p>Some Text...</p>
    <p>Some Text...</p>    
  </div>
</div>
本文链接:https://www.f2er.com/3162293.html

大家都在问