如何正确处理错误并防止显示文件夹目录

时间:2018-12-30 09:35:49

标签: javascript graphql apollo-server

我正在尝试使用Apollo Server 2为我的学校项目从头创建自己的后端服务器,并尝试创建用于授权和身份验证的安全功能,但不确定是否应该这样做

我不确定我是否可以为用户授权正确处理错误,并且当出现错误时,服务器将使用包括服务器文件夹目录在内的stacktrace响应错误。

我尝试了很多方法,到目前为止,使用try catch块将我得到的错误最小化。

Auth.js / auth

import JWTR from 'jwt-redis'
import Redis from 'ioredis'

const redis = new Redis({
  ....
})

const jwtr = new JWTR(redis)
const token = req => req.headers.authorization.replace('Bearer', '').trim()
export const attemptSignIn = async (email, password) => {
    var user = await User.findOne({ email })

    if (!user || !await user.matchesPassword(password)) {
        throw new AuthenticationError(INVALID_CREDENTIAL)
}

const payload = await jwtr.sign({ id: user.id }, JWT_SECRET)
user.token = payload
return user
}

export const decodeAuthToken = async req => {
    if (!token(req)) {
        throw new AuthenticationError(NO_JWT)
    }
    try {
        const payload = await jwtr.verify(token(req), JWT_SECRET)
        return payload
    } catch (error) {
        throw new AuthenticationError(INVALID_JWT)
    }
}

export const checkAuthToken = async req => {
    console.log(token(req))
    if (!token(req)) {
        throw new AuthenticationError(NO_JWT)
    }
    try {
        const payload = await jwtr.verify(token(req), JWT_SECRET)
        if (payload) {
            return true
        }
    } catch (error) {
        throw new AuthenticationError(INVALID_JWT)
    }
    return false
}

user.js / resolvers

import * as Auth from '../auth'
users: async (root, args, { req }, info) => {
    // Auth.checkSignedIn(req)
    await Auth.checkAuthToken(req)
    return User.find({})
},

我希望收到此错误消息,但没有在错误中获取此特定信息-> / Users / firmanjamal / Desktop / School Project / FYP / backend / src / auth.js:68:11)

"    at Proxy.checkAuthToken (/Users/firmanjamal/Desktop/School Project/FYP/backend/src/auth.js:68:11)",
        "    at process.internalTickCallback (internal/process/next_tick.js:77:7)"

"errors": [
{
  "message": "The JWT you supply is not valid or already expired.",
  "locations": [
    {
      "line": 2,
      "column": 3
    }
  ],
  "path": [
    "user"
  ],
  "extensions": {
    "code": "UNAUTHENTICATED",
    "exception": {
      "stacktrace": [
        "AuthenticationError: The JWT you supply is not valid or already expired.",
        "    at Proxy.checkAuthToken (/Users/firmanjamal/Desktop/School Project/FYP/backend/src/auth.js:68:11)",
        "    at process.internalTickCallback (internal/process/next_tick.js:77:7)"
      ]
    }
  }
}
],

1 个答案:

答案 0 :(得分:2)

来自docs

  

要为生产禁用堆栈跟踪,请将debug:false传递给Apollo服务器构造函数,或将NODE_ENV环境变量设置为“ production”或“ test”。请注意,这将使您的应用程序无法使用堆栈跟踪。

换句话说,默认情况下包括堆栈跟踪,但仅当NODE_ENV环境变量未设置为production时才包括。如果即使在开发过程中也要忽略堆栈跟踪,请按以下方式创建ApolloServer:

new ApolloServer({ typeDefs, resolvers, debug: false })