Errors

error - is an unintentional condition in script, which prevents the program from continuing

when speaking about errors, it's important to know that JavaScript engine first reads the code, and then runs it

parse-time errors - errors that occur on the reading phase

  • such errors are unrecoverable


runtime errors - errors that occur on the running phase, i.e. in code, which is considered valid

exception - a specific type of runtime error that can be caught and handled with try...catch

  • uncaught error stops script execution, which is considered as crash

try...catch

try {
  // try to execute the code
} catch (error) {
  // handle errors
} finally {
  // execute always
}

try...catch - mechanism used to handle exceptions

  • try, catch and finally blocks create their own scope
  • try...catch might be put inside another try
  • try...catch works synchronously, therefore it will not catch exception happening in async (scheduled) code
  • if needed to catch async error, async function call result should be awaited in "try" block


try block - wraps a code where an error can potentially happen

  • if error occurs, the rest of "try" of ignored. instead, "catch" is executed


catch block - provides code which should be run in response to an error

  • as an example, can be used to send a new request; send error data to error logging service
  • accepting error object in catch is optional


finally block - provides code which should always be run

window.onerror - global error handler. this function runs in case of any uncaught error

  • e.g. window.onerror = function(message, url, line, column, error) {...}; - set new global error handler


rethrowing - pattern of error handling. catch block should know how to handle the particular error type. if it doesn't recognize a type, it should rethrow error

Built-in Errors

TypeError - an error that occurs when an operation is performed on a value of an inappropriate type

  • e.g.
  • Cannot read properties of undefined
  • Undefined is not a function

Custom Errors

throw operator - is used to generate an error and manually throw it

  • technically, anything can be used as a custom error, including primitive
  • good practice is to throw object with "name" and "message" properties, in order to stay compatible with built-in errors


new Error() - constructor for creation of standard error object

  • Error() equals new Error()
  • there are also constructors for more specific errors: SyntaxError, ReferenceError, TypeError, etc.
  • standard error object contains:
  • name
  • message
  • stack
const error = new SyntaxError('Machine can not read what you wrote. Be more accurate.');

error.name === 'SyntaxError'; // true
error.message === 'Machine can not read what you wrote. Be more accurate.'; // true

throw error;
;