profileRyan KesPGP keyI build stuffEmailGithubTwitterLast.fmMastodonMatrix

JavaScript Custom Error Types

Introduction

Introduced in ES6, JavaScript allows you to create your own custom error objects.

Syntax

class MyError extends Error {}

function tralala() {
  throw new MyError("blahblahblah")
}

try {
  tralala()
} catch (e) {
  if (e instanceof MyError) {
    console.log("Something went wrong with tralala")
  } else {
    throw e
  }
}