Cant access values in my EXPRESS / NodeJs response error [String: 'Error: Request returned error code: 404

自闭症网瘾萝莉.ら 提交于 2020-01-06 06:43:49

问题


i am trying to access values in my express response error. When I console.log the error like this...

app.use(function(err, req, res, next){
    console.log(err)
});

The console looks like the following

[String: 'Error: Request returned error code: 404 and body: {"status":404,"title":"No option(s) were found with this query.","type":"https://developer.bigcommerce.com/api#api-status-codes"}']

For Example; how do i access err.title so i can send this to the client.

reference this question for more Parse Error response in Express NodeJS app


回答1:


If I'm not wrong, express uses a generic error object defined in the standard, and there are only three properties:

Error.prototype.constructor
Specifies the function that created an instance's prototype.
Error.prototype.message
Error message.
Error.prototype.name
Error name.

Some libraries (like mongoose for example) use a custom error object, so you can access to more error details (and properties), if this is your case, you could try to look for an "Error handling" chapter in the official docs of that library, and see if you have more details in the error object. In this cases I think you won't use the err object provided by express but an err provided by the library method which rises the error, somewhat like:

...
app.use((err, req, res, next)=>{
 library.method((err1, data)=>{
  console.log(err1);// use this error object
 })
})
... 


来源:https://stackoverflow.com/questions/50191271/cant-access-values-in-my-express-nodejs-response-error-string-error-reques

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!