Javascript create error type

Correct way to create custom errors in javascript

What is the correct way to define a custom error in JavaScript? Searching through SO I’ve found about 6 different ways to define a custom error, but I’m unsure as to the (dis)advantages to each of them. From my (limited) understanding of prototype inheritance in JavaScript, this code should be sufficient:

function CustomError(message) < this.name = "CustomError"; this.message = message; >CustomError.prototype = Object.create(Error.prototype); 

that was the main SO question that confused me. the highest ranked answer lists two different ways for the custom error to inherit from the Error object, neither of which is using the Object.create() method. the other answers seem to be variations of this theme.

Object.create is merely a new way of doing CustomError.prototype = new Error() — developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

4 Answers 4

The simplest of course, and in my opinion, the best to use unless you need more complex error reporting/handling is this:

throw Error("ERROR: This is an error, do not be alarmed.") 

Usually I just use throw new Error(. ) , but for custom errors I find the following code works pretty well and still gives you stack traces on V8, i.e. in Chrome and node.js (which you don’t get just by calling Error.apply() as suggested in the other answer):

function CustomError(message) < // Creates the this.stack getter if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor) this.message = message; >CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.constructor = CustomError; CustomError.prototype.name = 'CustomError'; 

For more info, see these links:

Читайте также:  Java jvm option heap

thanks. this seems to work correctly while also defining this.stack where available. the only change i’ll make in my own code is to also define this.name in the constructor.

Good suggestion; I’ve added that in (did it on the prototype since the name is the same for all instances, but it doesn’t really matter).

Note: for fuller compatibility with IE, a few other things are needed; see stackoverflow.com/a/8460753/560114.

This script depicts all the possible mechanisms for creating and using custom errors in JavaScript.

Also to get a complete understanding, it’s essential to have an understanding of prototypal inheritance and delegation in JavaScript. I wrote this article which explains it clearly. https://medium.com/@amarpreet.singh/javascript-and-inheritance-90672f53d53c

function add(x, y) < if (x && y) < return x + y; >else < /** * * the error thrown will be instanceof Error class and InvalidArgsError also */ throw new InvalidArgsError(); // throw new Invalid_Args_Error(); >> // Declare custom error using using Class class Invalid_Args_Error extends Error < constructor() < super("Invalid arguments"); Error.captureStackTrace(this); >> // Declare custom error using Function function InvalidArgsError(message) < this.message = `Invalid arguments`; Error.captureStackTrace(this); >// does the same magic as extends keyword Object.setPrototypeOf(InvalidArgsError.prototype, Error.prototype); try< add(2) >catch(e) < // true if(e instanceof Error)< console.log(e) >// true if(e instanceof InvalidArgsError) < console.log(e) >> 

Источник

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 — менее читаема.

Источник

Оцените статью