Error Properties Javascript
Contents |
& Guides Learn the Web Tutorials References Developer Guides Accessibility Game development ...more docs Mozilla Docs Add-ons Firefox WebExtensions Developer ToolsFeedback Get Firefox help Get javascript error object web development help Join the MDN community Report a content problem Report a
Javascript Try Catch
bug Search Search Languages Català (ca) Deutsch (de) Español (es) Français (fr) Bahasa Indonesia (id) 日本語 (ja) 한국어 javascript exception properties (ko) Polski (pl) Português (do Brasil) (pt-BR) Русский (ru) 中文 (简体) (zh-CN) 正體中文 (繁體) (zh-TW) Add a translation Edit Advanced Advanced History Print this article MDN Web technology For developers JavaScript JavaScript
Javascript Error Handling
reference Standard built-in objects Error Your Search Results ariyankhan josephmcasey AlexanderFradiani fscholz mondwan SphinxKnight janosch-x davidchase Mingun shawnacscott Sheppy ethertank Nickolay evilpie trevorh teoli davidbourguignon secoif DomenicDenicola dgchurchill timemachine3030 Sevenspade Potappo Sephr Brettz9 Mgjbot Allanbonadio Ptak82 JustinLudwig Error In This Article SyntaxParametersDescriptionError typesPropertiesMethodsError instancesPropertiesStandard propertiesVendor-specific extensionsMicrosoftMozillaMethodsExamplesThrowing a generic errorHandling a specific errorCustom Error TypesSpecificationsBrowser compatibilitySee also The Error constructor creates an error object. javascript error attributes Instances of Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types. Syntax new Error([message[, fileName[, lineNumber]]]) Parameters message Optional. Human-readable description of the error. fileName Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor. lineNumber Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation. Description Runtime errors result in new Error objects being created and thrown. This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see Error.prototype. Error types Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements. EvalError Creates an instance representing an error that occurs regarding the global function eval(). InternalError Creates an instance representing an error that occurs when an internal error in the
& Guides Learn the Web Tutorials References Developer Guides Accessibility Game development ...more docs Mozilla Docs Add-ons Firefox WebExtensions Developer ToolsFeedback Get Firefox help
Javascript Alert Properties
Get web development help Join the MDN community Report a content problem Report
Javascript Array Properties
a bug Search Search Languages Català (ca) Deutsch (de) Français (fr) 日本語 (ja) Русский (ru) 中文 (简体) (zh-CN) define inaccuracy Add a translation Edit Advanced Advanced History Print this article MDN Web technology For developers JavaScript JavaScript reference Standard built-in objects Error Error.prototype.toString() Your Search Results eduardoboucas fscholz Mingun Waldo getify https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error Sheppy ethertank evilpie Sevenspade Error.prototype.toString() In This Article SyntaxReturn valueDescriptionExamplesSpecificationsBrowser compatibilitySee also The toString() method returns a string representing the specified Error object. Syntax e.toString() Return value A string representing the specified Error object. Description The Error object overrides the Object.prototype.toString() method inherited by all objects. Its semantics are as follows (assuming Object and String have their original values): Error.prototype.toString = function() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toString { 'use strict'; var obj = Object(this); if (obj !== this) { throw new TypeError(); } var name = this.name; name = (name === undefined) ? 'Error' : String(name); var msg = this.message; msg = (msg === undefined) ? '' : String(msg); if (name === '') { return msg; } if (msg === '') { return name; } return name + ': ' + msg; }; Examples var e = new Error('fatal error'); console.log(e.toString()); // 'Error: fatal error' e.name = undefined; console.log(e.toString()); // 'Error: fatal error' e.name = ''; console.log(e.toString()); // 'fatal error' e.message = undefined; console.log(e.toString()); // 'Error' e.name = 'hello'; console.log(e.toString()); // 'hello' Specifications Specification Status Comment ECMAScript 1st Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.1. ECMAScript 5.1 (ECMA-262)The definition of 'Error.prototype.toString' in that specification. Standard ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Error.prototype.toString' in that specification. Standard ECMAScript 2017 Draft (ECMA-262)The definition of 'Error.prototype.toString' in that specification. Draft Browser compatibility Desktop Mobile Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari Basic support (Yes) (Yes) (Yes) (Yes) (Yes) Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Op
form of try..catch..finally try..catch..finally and return The throw statement A validator example Changes in the usage pattern Comparison Exception analysis and rethrow Summary Understanding exception is important to object-oriented programming in general and JavaScript in particular. Exceptions is a special, very powerful way to deal http://javascript.info/tutorial/exceptions with errors. Check-first error handling Let's take a bad code as an example. Like this: https://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/ nonexistant() In the example above, a non-existing variable is accessed. What should a program do in this case? The simple and very old concept is that the program dies. Let's say we want to evade that sorrowful happening. So, what to do in case when the variable may be undefined? The simple way is to check it. Something like that: if (window.func) javascript error { func() } There still may be an error if window.func is not a function. So we'll need to check for it as well: if (typeof(func) == 'function') { func() } In the code above, typeof ensures that the variable exists and it is actually a function. Hopefully we performed all necessary checks to ensure that running func is safe. But what if it isn't? What if the func body has errors? Again, we want to handle the error properties javascript error, not let the script just die. And here the try..catch construct kicks in. The try..catch construct The try..catch approaches the error handling from another side. Instead of "check if all ok, then do" approach, we try then catch errors. A completely different way to handle errors which replaces the checking code. The function example would look like: try { func() } catch(e) { alert(e) } If an error occurs inside the try block, the control is passed to the catch(e) section. It's argument e is assigned to a special exception object which contains the information about what happened. The variable e contains an instance of Error object (or it's inheritant like TypeError, ReferenceError etc). The error properties are little bit different between browsers, see Error in MDN and Error in MSDN for details. But there are always basic attributes: name The error type, for browser-generated errors it matches error constructor function, like TypeError, ReferenceError etc. message The text message which tells more about the error. Now let's go further and add other statements into try section. In the example below, both name and message are printed. try { var a = 5 var res = func(a) if (res > 0) doA() else doB() } catch(e) { alert("name:" + e.name + "\nmessage:" + e.message) } Do you know one cool thing about the try..catch? There are errors which can only be ca
I got a lot of responses and follow-up questions, so I thought I'd continue the discussion by explaining a little more about how to throw your own errors. To review, the basic syntax is: throw new Error("message"); This works in all browsers and will display the error information in the same way it would any unintentional JavaScript error. The "message" string is stored in the message property of the object (which is what the browser uses to display the message). Periodically, I see people throwing errors by just providing the string, such as this: throw "message"; Doing so will cause an error to be thrown, but not all browsers respond the way you'd expect. Firefox, Opera, and Chrome each display an "uncaught exception" message and then include the message string. Safari and Internet Explorer simply throw an "uncaught exception" error and don't provide the message string at all. Clearly, this is suboptimal from a debugging point of view. Of course, you can throw any type of data that you'd like. There are no rules prohibiting specific data types: throw { name: "Nicholas" }; throw true; throw 12345; throw new Date(); The only thing to remember is that throwing any value will result in an error if it's not caught via a try-catch statement. Firefox, Opera, and Chrome all call String() on the value that was thrown to display something logical as the error message; Safari and Internet Explorer do not. The only surefire way to have all browsers display your custom error message is to use an Error object. ECMA-262, 3rd Edition actually specifies seven error object types. These are used by the JavaScript engine when various error conditions occur and can also be manually created: Error - base type for all errors. Never actually thrown by the engine. EvalError - thrown when an error occurs during execution of code via eval() RangeError - thrown when a number is outside the bounds of its range. For example, trying to create an array with -20 items (new Array(-20)). These occur rarely during normal execution. ReferenceError - thrown when an object is expecte