0

I would like to keep all of error descriptions in a single .js file as a dictionary, so that I can display the appropriate description from the rest of my JavaScript web app. I am very new to JS web app development and I am wondering how to achieve this.

currently I have been trying this:

errorDesc.js:

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

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

main.js:

import {getResponseDescription} from "./errorDesc";

But in the console I get the following error: Uncaught SyntaxError: Unexpected token {

enter image description here

Kourosh
  • 588
  • 1
  • 12
  • 31
  • Is the file name missing `".js"` the issue? What line does the error message output? – guest271314 Feb 03 '19 at 16:59
  • @guest271314 the error is in main.js, I just added a screenshot. That's the error I get. – Kourosh Feb 03 '19 at 17:02
  • Can you reproduce the issue at plnkr https://plnkr.co? – guest271314 Feb 03 '19 at 17:03
  • 2
    FYI, it's silly to iterate through the dictionary. It's already indexed by key. Just do `return descriptions[name];`. And, there's no variable defined named `responses` so using that is clearly an error unless you're not showing us some of your code. – jfriend00 Feb 03 '19 at 17:05
  • @jfriend00 that's correct, I edited as you just mentioned. However the error is still there. – Kourosh Feb 03 '19 at 17:12
  • @guest271314 You can view the same error here: https://plnkr.co/edit/z5rl1khrkZeXt19eeWkR – Kourosh Feb 03 '19 at 17:24
  • 1
    @Kourosh There is no `"messages.js"` file and no ` – guest271314 Feb 03 '19 at 17:28
  • @guest271314 Thank you, what was missing was "type='module'" when importing the main.js script in the html file. Once added the type, the error went away. Thank you _/\_ – Kourosh Feb 03 '19 at 17:41

1 Answers1

0

I will suggest you have a file consist of error classes (used to set an error message and error name) which extend Error class and in the constructor assign the error message and error name to the object e.g.

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

after that set, the status code based on the type of error and return e.g.

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 });
}

wherever you encounter error create a new instance of the type of error class

next(new AuthorizationError('Username or password do not match'));
anu-007
  • 16
  • 1
  • 2