![](/img/trans.png)
[英]What is the best way to pass server side variables to JavaScript on the client side?
[英]What's the best way to deal with an error in the server side and in the client side using nodejs + express
我想知道在响应中处理错误的最佳方法 - 请求。 我有这条路线接收请求:
app.get('/getInfo', function (req, res, next) {
let obj = {}
try {
obj = {
...
date: lastUpdatedDate('./utils/appVersion.js'),
...
}
res.status(200).send(obj)
} catch (error) {
console.log(error.message)
res.send({error: "The data wasn't load"})
}
})
并且这个函数在哪里发出请求
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
console.log(error)
})
}
如果它出现在服务器端,那么处理错误的最佳方法是什么? 让我们知道在这个代码块中该目录不存在: lastUpdatedDate('./directoreyDoesntExists/appVersion.js'),
所以我的代码转到catch
块。
我应该发送这样的错误:
res.send({error: "The data wasn't load"})
我应该设置这样的状态吗?
res.status(500).send({error: "The data wasn't load"})
或者我应该使用不同的状态代码设置状态?
基于此,在我的前端方法getInfo()
处理它的最佳方法是什么来获取错误并在Web界面上显示错误消息?
我应该像这样在.then
块中做一个if else
吗?
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
if(resp.status === 200){
this.appInfoHandler(resp.data)
}else if (resp.status === 400){
//print error message on web interface
}else if (resp.status === 500){
//print error message on web interface
})
.catch(function (error) {
console.log(error)
})
或者我应该像这样直接在catch
块中处理这个错误
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
//print error message on web interface
})
}
对于这种情况
res.send({error: "The data wasn't load"})
VS
res.status(500).send({error: "The data wasn't load"})
发送状态只是更详细,但两者都可以。 检查正确的方法来设置响应状态和JSON内容
对于这种情况,取决于您需要什么
then(resp => {
if(resp.status === 200){
this.appInfoHandler(resp.data)
}else if (resp.status === 400){
//print error message on web interface
}else if (resp.status === 500){
//print error message on web interface
})
.catch(function (error) {
console.log(error)
})
VS
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
//print error message on web interface
})
}
您可以处理将它们发送到catch块的所有错误
else if (resp.status === 400){
//print error message on web interface
不在此处打印错误,而是抛出一个新错误,将其发送到catch块
throw new ApiError("UserNotFount",400,"not found");
throw new Error('Error 400, not found');
对于这种情况
res.send({error: "The data wasn't load"})
VS
res.status(500).send({error: "The data wasn't load"})
我建议发送错误以及状态代码,因为这对客户端更具描述性。
而对于第二种情况
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
if(resp.status === 200){
this.appInfoHandler(resp.data)
}else if (resp.status === 400){
//print error message on web interface
}else if (resp.status === 500){
//print error message on web interface
})
.catch(function (error) {
console.log(error)
})
VS
getInfo () {
axios.get(process.env.REACT_APP_HOST + '/getInfo')
.then(resp => {
this.appInfoHandler(resp.data)
})
.catch(function (error) {
//print error message on web interface
})
}
在这种情况下,我建议在出现错误时直接使用catch块,因为响应状态取决于错误而不是相反
任何其他200的状态代码都意味着不成功,所以你不需要使用那些if-else语句。 更好的选择是捕获错误并按原样发送响应。 这样做的好处是,您可以在不对代码进行硬编码的情况下收到错误类型。 (例如,我们将此处的状态代码视为400不成功)
.catch(function (error) {
//print error message on web interface
res.status(400).send(JSON.stringify(error, undefined, 2));
});
通过使用stringify方法,您还可以在控制台上打印确切的错误。
.catch(function (error) {
console.log(JSON.stringify(error, undefined, 2));
});
stringify方法中的参数如下:
错误对象
undefined:包含用于过滤对象中键的键的数组(此处为error)。 此数组中存在的所有键只是未滤除的键。
2:用于在对象表示中引入空格
作为REST Api的初学者,您应该看一下指南 - 微软是非常合法的: https : //docs.microsoft.com/en-us/azure/architecture/best-practices/api-design 。
基本上,您需要为每个请求返回正确的HTTP代码,请查看https://http.cat/ - 例如,如果请求格式错误,则返回400,如果用户未经授权则返回401:
if (!req.body.name) {
res.status(400).send({ error: 'missing user name' }); // 400 bad request
}
const user = getUser(req.body.name, req.body.pass);
if(!user) {
res.status(401).send({ error: 'user does not exist' }); // 401 unauthorized
}
try {
const token = createToken(user);
// better to set a cookie
res.status(200).send({ token }); // 200 success
} catch(e) {
res.status(500).send({ erroe: e.message }); // 500 internal error
}
if(isTeapot) {
res.status(418).send({ error: 'I can only make tea' }); // 418 teapot, totally real
}
为了方便起见,有很多库可以帮助您生成更好的错误消息并更好地处理错误,我最喜欢的一个是庆祝
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.