Form

Error

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.

Description

Runtime errors result in new Error objects being created and thrown.

Error is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage() .

Error types

Besides the generic Error constructor, there are other core error constructors in JavaScript. For client-side exceptions, see Exception handling statements.

Creates an instance representing an error that occurs regarding the global function eval() .

Creates an instance representing an error that occurs when a numeric variable or parameter is outside its valid range.

Creates an instance representing an error that occurs when de-referencing an invalid reference.

Creates an instance representing a syntax error.

Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

Creates an instance representing several errors wrapped in a single error when multiple errors need to be reported by an operation, for example by Promise.any() .

Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. «too much recursion».

Constructor

Creates a new Error object.

Static methods

A non-standard V8 function that creates the stack property on an Error instance.

A non-standard V8 numerical property that limits how many stack frames to include in an error stacktrace.

Error.prepareStackTrace() Non-standard Optional

A non-standard V8 function that, if provided by usercode, is called by the V8 JavaScript engine for thrown exceptions, allowing the user to provide custom formatting for stacktraces.

Instance properties

These properties are defined on Error.prototype and shared by all Error instances.

The constructor function that created the instance object. For Error instances, the initial value is the Error constructor.

Represents the name for the type of error. For Error.prototype.name , the initial value is «Error» . Subclasses like TypeError and SyntaxError provide their own name properties.

A non-standard property for a stack trace.

These properties are own properties of each Error instance.

Error cause indicating the reason why the current error is thrown — usually another caught error. For user-created Error objects, this is the value provided as the cause property of the constructor’s second argument.

A non-standard Mozilla property for the column number in the line that raised this error.

A non-standard Mozilla property for the path to the file that raised this error.

A non-standard Mozilla property for the line number in the file that raised this error.

Error message. For user-created Error objects, this is the string provided as the constructor’s first argument.

Instance methods

Returns a string representing the specified object. Overrides the Object.prototype.toString() method.

Examples

Throwing a generic error

Usually you create an Error object with the intention of raising it using the throw keyword. You can handle the error using the try. catch construct:

try  throw new Error("Whoops!"); > catch (e)  console.error(`$e.name>: $e.message>`); > 

Handling a specific error type

You can choose to handle only specific error types by testing the error type with the error’s constructor property or, if you’re writing for modern JavaScript engines, instanceof keyword:

try  foo.bar(); > catch (e)  if (e instanceof EvalError)  console.error(`$e.name>: $e.message>`); > else if (e instanceof RangeError)  console.error(`$e.name>: $e.message>`); > // etc. else  // If none of our cases matched leave the Error unhandled throw e; > > 

Differentiate between similar errors

Sometimes a block of code can fail for reasons that require different handling, but which throw very similar errors (i.e. with the same type and message).

If you don’t have control over the original errors that are thrown, one option is to catch them and throw new Error objects that have more specific messages. The original error should be passed to the new Error in the constructor’s options parameter as its cause property. This ensures that the original error and stack trace are available to higher-level try/catch blocks.

The example below shows this for two methods that would otherwise fail with similar errors ( doFailSomeWay() and doFailAnotherWay() ):

function doWork()  try  doFailSomeWay(); > catch (err)  throw new Error("Failed in some way",  cause: err >); > try  doFailAnotherWay(); > catch (err)  throw new Error("Failed in another way",  cause: err >); > > try  doWork(); > catch (err)  switch (err.message)  case "Failed in some way": handleFailSomeWay(err.cause); break; case "Failed in another way": handleFailAnotherWay(err.cause); break; > > 

Note: If you are making a library, you should prefer to use error cause to discriminate between different errors emitted — rather than asking your consumers to parse the error message. See the error cause page for an example.

Custom error types can also use the cause property, provided the subclasses’ constructor passes the options parameter when calling super() . The Error() base class constructor will read options.cause and define the cause property on the new error instance.

class MyError extends Error  constructor(message, options)  // Need to pass `options` as the second parameter to install the "cause" property. super(message, options); > > console.log(new MyError("test",  cause: new Error("cause") >).cause); // Error: cause 

Custom error types

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. This results in cleaner and more consistent error handling code.

See «What’s a good way to extend Error in JavaScript?» on StackOverflow for an in-depth discussion.

Warning: Builtin subclassing cannot be reliably transpiled to pre-ES6 code, because there’s no way to construct the base class with a particular new.target without Reflect.construct() . You need additional configuration or manually call Object.setPrototypeOf(this, CustomError.prototype) at the end of the constructor; otherwise, the constructed instance will not be a CustomError instance. See the TypeScript FAQ for more information.

Note: Some browsers include the CustomError constructor in the stack trace when using ES2015 classes.

class CustomError extends Error  constructor(foo = "bar", . params)  // Pass remaining arguments (including vendor specific ones) to parent constructor super(. params); // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace)  Error.captureStackTrace(this, CustomError); > this.name = "CustomError"; // Custom debugging information this.foo = foo; this.date = new Date(); > > try  throw new CustomError("baz", "bazMessage"); > catch (e)  console.error(e.name); // CustomError console.error(e.foo); // baz console.error(e.message); // bazMessage console.error(e.stack); // stacktrace > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • A polyfill of Error with modern behavior like support cause is available in core-js
  • throw
  • try. catch
  • The V8 documentation for Error.captureStackTrace() , Error.stackTraceLimit , and Error.prepareStackTrace() .

Found a content problem with this page?

This page was last modified on Jun 18, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

I want to alert an error message

I am currently using an alert to tell the user if their email input is not valid but I would like to alert error message.

4 Answers 4

You can use HTML5 validation to validate an email input.

The ‘required’ property makes it so that an email is both required and formatted correctly before being submitted.

There are several ways an email address entered into a text field can be validated; some are more comprehensive and can be manipulated, others can be built-in. Usually, a simple HTML5 validation is quick and effective and can be achieved in one line of code. However, it is also possible to do it in JavaScript as outlined below.

Using Built-In HTML5 Attributes To Validate

As Fin has previously said:

You can use HTML5 validation to validate an email input.

The ‘required’ property makes it so that an email is both required and formatted correctly before being submitted.

With this in mind, you can add this to your code to produce the following:

      function logOptions() < var s = document.getElementsByName('Interests')[0]; var text = s.options[s.selectedIndex].text; console.log(text); >function logEmail() < console.log(document.getElementById('emailinput').value); >function myFunction() 

Stay up to date with ecommerce trends
with Apples's newsletter

Subscribe for free marketing tips

-->

JavaScript Validation

You can place this code inside your script tags in the head of the document:

function validateEmail(emailField)< var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z])$/; if (reg.test(emailField.value) == false) < alert('Invalid Email Address'); return false; >return true; > 

. and replace your email input feild with this line:

Источник

How do you send console messages and errors to alert?

I would like to pass errors to an alert to warn the user they made mistake in their code even if they don’t have console open.

 var doc=(frame.contentWindow.document || obj.contentDocument|| obj.contentWindow); var head = doc.getElementsByTagName('head')[0]; var scriptElement = doc.createElement('script'); scriptElement.setAttribute('type', 'text/javascript'); scriptElement.text = scripts; try < head.appendChild(scriptElement); >catch(e)

The appendChild throws an error when the scripts contain an error. It goes straight to the console though, and I want it to display in an alert, because it is for kids and they might not check the console. The try catch block does not catch the error. I tried it with eval(scripts).

this does work but it means that the code is executed twice, and that is very inconvenient in some cases. I tried monkey patching the console.error:

 console.log=function() console.error=function()

but that only works when I literally use console.error. Not when an actual error is thrown. What function sends the error to the console in the case of a real error,if it isn’t console.error? and can I access it and change it? Any ideas? Help would be really appreciated. Thanks Jenita

3 Answers 3

Whilst try . catch will work on the code that the script runs initially, as Jenita says it won’t catch Syntax Errors, and also it won’t catch errors thrown by callback functions which execute later (long after the try-catch has finished). That means no errors from any functions passed to setTimeout or addEventListener .

However, you can try a different approach. Register an error listener on the window.

window.addEventListener("error", handleError, true); function handleError(evt) < if (evt.message) < // Chrome sometimes provides this alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename); >else < alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target)); >> 

This will be called when an exception is thrown from a callback function. But it will also trigger on general DOM errors such as images failing to load, which you may not be interested in.

It should also fire on Syntax Errors but only if it was able to run first so you should put it in a separate script from the one that may contain typos! (A Syntax Error later in a script will prevent valid lines at the top of the same script from running.)

Unfortunately, I never found a way to get a line number from the evt in Firefox. (Edit: Poke around, I think it might be there now.)

I discovered this when trying to write FastJSLogger, an in-page logger I used back when the browser devtools were somewhat slow.

Desperate to catch line numbers, I started to experiment with wrappers for setTimeout and addEventListener that would re-introduce try-catch around those calls. For example:

var realAddEventListener = HTMLElement.prototype.addEventListener; HTMLElement.prototype.addEventListener = function(type,handler,capture,other) < var newHandler = function(evt) < try < return handler.apply(this,arguments); >catch (e) < alert("error handling "+type+" event:"+e.message +" linenumber:"+e.lineNumber); >>; realAddEventListener.call(this,type,newHandler,capture,other); >; 

Obviously this should be done before any event listeners are registered, and possibly even before libraries like jQuery are loaded, to prevent them from grabbing a reference to the real addEventListener before we have been able to replace it.

Источник

Читайте также:  Показать код html на странице
Оцените статью