繁体   English   中英

在单独的JS文件中访问字典并检索值

[英]Accessing a dictionary in a separate JS file and retrieve value

我想将所有错误描述作为字典保存在单个.js文件中,以便可以从我的JavaScript Web应用程序的其余部分显示适当的描述。 我对JS Web应用程序开发非常陌生,我想知道如何实现这一目标。

目前,我一直在尝试:

errorDesc.js:

var descriptions = {
    errorCode00 : "description",
    errorCode02 : "description",
    errorCode03 : "description"
}

export function getResponseDescription(name) {
    return descriptions[name];
}

main.js:

import {getResponseDescription} from "./errorDesc";

但是在控制台中,我收到以下错误:Uncaught SyntaxError:Unexpected token {

在此处输入图片说明

我建议您使用一个由错误类(用于设置错误消息和错误名称)组成的文件,该文件扩展了Error类,并在构造函数中将错误消息和错误名称分配给对象,例如

class AuthorizationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AuthorizationError';
    this.message = message;
  }
}
// classes of other error types

设置完之后,根据错误的类型返回状态代码,例如

const errorHandler = (error, req, res, next) => {
  const message = error.message || 'Something went wrong';
  let status = null;
  switch(error.name) {
  case 'AuthorizationError':
    status = 403;
    break;
  // other error types
  }
  res.status(status).json({ message });
}

无论何时遇到错误,都将创建错误类类型的新实例

next(new AuthorizationError('Username or password do not match'));

暂无
暂无

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

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