Javascript class name error

Error и стандартные ошибки

Какие бывают стандартные ошибки в JavaScript и как создавать собственные типы ошибок.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Программа может работать правильно, только если код написан корректно и не содержит ошибок. JavaScript умеет обрабатывать некорректный код и сообщать об ошибке в коде. Существует семь встроенных видов ошибок, также можно создать свои собственные. Встроенные ошибки генерируются самим движком JavaScript при выполнении программы, а пользовательские — создаются с помощью конструктора Error . Оба типа ошибок можно ловить в конструкции try . . . catch .

Как понять

Скопировать ссылку «Как понять» Скопировано

Error

Скопировать ссылку «Error» Скопировано

 new Error('Общая ошибка. Проверьте код') new Error('Общая ошибка. Проверьте код')      

Вызов конструктора возвращает объект ошибки со следующими свойствами:

  • message представляет человекопонятное описание ошибки для встроенных типов ( Syntax Error , Type Error и так далее) и переданное в конструктор значение для общего типа Error .
  • name — имя типа (класса) ошибки.
 const commonError = new Error('Общая ошибка. Проверьте код') console.log(commonError.message)// 'Общая ошибка. Проверьте код' console.log(commonError.name)// 'Error' const commonError = new Error('Общая ошибка. Проверьте код') console.log(commonError.message) // 'Общая ошибка. Проверьте код' console.log(commonError.name) // 'Error'      

Нестандартное свойство stack показывает, на какой строке кода возникла ошибка. Первая строка отформатирована как : , и за ней следует серия кадров стека (каждая строка начинается с «at»).

ReferenceError: FAIL is not defined at Constraint.execute (deltablue.js:525:2) at Constraint.recalculate (deltablue.js:424:21) at Planner.addPropagate (deltablue.js:701:6) at Constraint.satisfy (deltablue.js:184:15) at Planner.incrementalAdd (deltablue.js:591:21) at Constraint.addConstraint (deltablue.js:162:10) at Constraint.BinaryConstraint (deltablue.js:346:7) at Constraint.EqualityConstraint (deltablue.js:515:38) at chainTest (deltablue.js:807:6) at deltaBlue (deltablue.js:879:2)

Встроенные ошибки

Скопировать ссылку «Встроенные ошибки» Скопировано

SyntaxError

Скопировать ссылку «SyntaxError» Скопировано

Чаще всего встречаются опечатки — неправильные названия методов, лишние или отсутствующие точки с запятой или скобочки и так далее. Такой тип ошибок называется «синтаксическим», Syntax Error :

 console.log(;)// SyntaxError: Unexpected token ';' console.log(()// SyntaxError: missing ) after argument list console.log(;) // SyntaxError: Unexpected token ';' console.log(() // SyntaxError: missing ) after argument list      

ReferenceError

Скопировать ссылку «ReferenceError» Скопировано

Если попытаться обратиться к несуществующей переменной, произойдёт ошибка Reference Error :

 console.log(name)// ReferenceError: name is not defined console.log(name) // ReferenceError: name is not defined      

TypeError

Скопировать ссылку «TypeError» Скопировано

Если попытаться обратиться к несуществующему свойству, произойдёт ошибка Type Error :

 console.log(null.length)// TypeError: Cannot read property 'length' of null undefined()// TypeError: undefined is not a function console.log(null.length) // TypeError: Cannot read property 'length' of null undefined() // TypeError: undefined is not a function      

RangeError

Скопировать ссылку «RangeError» Скопировано

Ошибка для значений, которые выходят за диапазон допустимого.

 new Array(10000000000)// RangeError: Недопустимая длина массива new Array(10000000000) // RangeError: Недопустимая длина массива      

URIError

Скопировать ссылку «URIError» Скопировано

Этот тип ошибок возникает при неправильном использовании обработки URI.

 decodeURIComponent('%')// URIError: URI malformed decodeURIComponent('%') // URIError: URI malformed      

Валидным считается URI, формат которого соответствует спецификации RFC 3986:

URI = scheme:[//authority]path[?query][#fragment]

EvalError

Скопировать ссылку «EvalError» Скопировано

EvalError представляет ошибку, возникающую в глобальной функции eval ( ) .

 eval( 'console.log(null.length)') eval( 'console.log(null.length)' )      

Эта ошибка в настоящее время не используется и остаётся для совместимости с предыдущими версиями JavaScript.

InternalError (не стандарт)

Скопировать ссылку «InternalError (не стандарт)» Скопировано

Ошибка внутри движка JavaScript. Не является стандартом и почти не используется. Например:

"InternalError: инициализатор массива слишком большой".

Собственный класс ошибок

Скопировать ссылку «Собственный класс ошибок» Скопировано

Можно расширять базовый класс Error и создавать собственные типы ошибок.

 class WrongDataTypeForSumError extends Error  constructor(message)  super(message) this.name = 'WrongDataTypeForSumError' >> const myCustomError = new WrongDataTypeForSumError('Невалидный тип данных для суммирования') class WrongDataTypeForSumError extends Error  constructor(message)  super(message) this.name = 'WrongDataTypeForSumError' > > const myCustomError = new WrongDataTypeForSumError('Невалидный тип данных для суммирования')      

Сгенерируем ошибку WrongDataTypeForSum Error в случае, если хотя бы один из аргументов функции sum — не число.

 function sum(a, b)  if (typeof a !== 'number' || typeof b !== 'number')  throw new WrongDataTypeForSumError('Невалидный тип данных для суммирования') > return a + b> console.log(sum('1', 2))// VM840:3 Uncaught WrongDataTypeForSumError: Невалидный тип данных для суммирования// at sum (:3:11)// at :9:13// WrongDataTypeForSumError @ VM830:3// sum @ VM840:3// (anonymous) @ VM840:9 function sum(a, b)  if (typeof a !== 'number' || typeof b !== 'number')  throw new WrongDataTypeForSumError('Невалидный тип данных для суммирования') > return a + b > console.log(sum('1', 2)) // VM840:3 Uncaught WrongDataTypeForSumError: Невалидный тип данных для суммирования // at sum (:3:11) // at :9:13 // WrongDataTypeForSumError @ VM830:3 // sum @ VM840:3 // (anonymous) @ VM840:9      

Функция будет выполняться только в том случае если оба аргумента будут числами, в противном случае функция будет возвращать ошибку WrongDataTypeForSum Error .

Собственные типы ошибок делают отладку более наглядной — например из имени WrongDataTypeForSum Error сразу понятно, что не так с кодом. Стандартная ошибка для таких случаев, Type Error — менее читаема.

Источник

Class name not working when called in Javascript?

I have a webpage in which there is a form with diffrent elements, in that there is also a Textfield which searches the names from the database and display it in a dropdown fashion. Below that there is one more field that which is a button , through which i can add new TextField , same as above. In that newly added TextField, I want the same AutoComplete feature as done above. I have given the class names all correct but it unable to fetch the Names and show it in a AutoComplete manner. NewUser.php

 $textval = json_encode($json); $foo = "var partnames=" . $textval; file_put_contents('autocomplete-Files/NewEntryValues.js', $foo); ?> . . . . . . . . 

As you can see above, the class in Input Tag is newentry and in the Javascript also newentry, I am fetch that newentry class name in a Another which takes care of Database connection and the AutoComplete Logic. So , how can the get that logic working in this script tag too ! autocomplete.js

$(function() < 'use strict'; var peopleArray = $.map(partnames, function (value, key) < return < value: value, data: key >; >); // Setup jQuery ajax mock: $.mockjax(< url: '*', responseTime: 2000, response: function(settings) < var query = settings.data.query, queryLowerCase = query.toLowerCase(), re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'), suggestions = $.grep(peopleArray, function(search) < // return country.value.toLowerCase().indexOf(queryLowerCase) === 0; return re.test(search.value); >), response = < query: query, suggestions: suggestions >; this.responseText = JSON.stringify(response); > >); // Initialize autocomplete with custom appendTo: $('.newentry').autocomplete(< lookup: peopleArray >); >); 

Источник

node.js simple project: ReferenceError: is not defined

enter image description here

I try to learn Node.js (ES6) but fail on require This is my structure: baseModel.js

"use strict"; class BaseModel < constructor(options = <>, data = []) < // class constructor this.name = 'Base' this.url = 'http://azat.co/api' this.data = data this.options = options >getName() < // class method console.log(`Class name: $`) > > 
"use strict"; require('./baseModel.js'); class AccountModel extends BaseModel < constructor(options, data) < super(, ['32113123123', '524214691']) //call the parent method with super this.name += 'Account Model' this.url +='/accounts/' > get accountsData() < //calculated attribute getter // . make XHR return this.data >> 
"use strict"; require('./AccountModel.js'); let accounts = new AccountModel(5) accounts.getName() console.log('Data is %s', accounts.accountsData); 

ReferenceError: BaseModel is not defined at Object. (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/AccountModel.js:5:28) at Module._compile (module.js:397:26) at Object.Module._extensions..js (module.js:404:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Module.require (module.js:353:17) at require (internal/module.js:12:17) at Object. (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/main.js:5:1) at Module._compile (module.js:397:26) at Object.Module._extensions..js (module.js:404:10)

Really strange, if I change require('./baseModel.js'); to other name, I get error that file not found so the path is written properly. Also defined permissions 777 - same thing, BaseModel is not defined Any Ideas?

Источник

Читайте также:  Php exception class code
Оцените статью