简体   繁体   English

为什么将 output 捕获为不同于变量的模板文字

[英]Why catch output as a template literal different from as a variable

I was wondering why the following outputs are seen based on each scenario:我想知道为什么会根据每种情况看到以下输出:

Assume i have a route with the following code:假设我有一条带有以下代码的路线:

app.get("/tasks", async (req, res) => {
  try {
    const tasks = await Task.find({});
    res.send(tasks)
  } catch (e) {
    res.status(500).send(`${e}`)
  }

Notice the last line in catch where i send the error, if I just type res.send(e) without the template literals a whole list of errors is generated with alot of errors.请注意 catch 中我发送错误的最后一行,如果我只键入 res.send(e) 而没有模板文字,则会生成包含大量错误的整个错误列表。

{
    "stringValue": "\"5ef23a969ba85e6fa63\"",
    "kind": "ObjectId",
    "value": "5ef23a969ba85e6fa63",
    "path": "_id",
    "reason": {}
}

BUT, if I use res.send( ${e} ) ( put the error as a literal) A simple line is generated with summary of the error.但是,如果我使用 res.send( ${e} ) (将错误作为文字)生成一个简单的行,其中包含错误摘要。 CastError: Cast to ObjectId failed for value "5ef23a969ba85e6fa63" at path "_id" for model "Task"

Is it a feature of template literals or.. ?它是模板文字的功能还是..?

The body parameter of send(parameter) can be: send(parameter)的 body 参数可以是:

  • a Buffer object缓冲器 object

  • a String一个字符串

  • an object一个 object

  • an Array数组

     res.send(Buffer.from('whoop')) res.send({ some: 'json' }) res.send('<p>some html</p>') res.status(404).send('Sorry, we cannot find that.') res.status(500):send({ error: 'something blew up' })

The template literal transforms your object into String : ${e} is a string.模板文字将您的 object 转换为String${e}是一个字符串。

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

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