Explain Codes LogoExplain Codes Logo

Custom exception type

javascript
exception-handling
error-objects
custom-exceptions
Nikita BarsukovbyNikita Barsukov·Jan 1, 2025
TLDR
class CustomError extends Error { constructor(message) { super(message); // "CustomError" isn't very creative, is it? 🤣 this.name = "CustomError"; } } // Now throw it like you throw a frisbee! 🥏 throw new CustomError("You found the error!"); // Remember to catch it though, with some smooth code moves try { // Potential code hiccup... } catch (error) { // *Mountain climber voice*: "Is it a custom error or just an amateur?" if (error instanceof CustomError) { // Handle that bad boy } else { // Send the others to the usual spot } }

Here we're sculpting an exception of our own, CustomError, by extending Error. This unique creation has a zesty name of its own, and we can throw and catch it just like any regular error (albeit with more flair ✨), thanks to our friend Mr. instanceof.

Exception enhancement 101

Significance of names in debugging wasteland

In the debugging wilderness, a name can be your compass. Names in error objects help in locating errors. Setting your own .name makes error tracking seem less like a wild goose chase 🦆!

Stack traces: the Hansel and Gretel breadcrumbs

A well-tailored exception keeps the stack trace intact. You'll leave no stone unturned in finding where that error crept in! Good news, if you extend Error, browsers will keep the trace for you, like an obedient pet. 🐕 For lingering cross-browser issues, you might have to call in the Error.captureStackTrace cavalry, assuming it's available.

if (Error.captureStackTrace) { Error.captureStackTrace(this, CustomError); }

Custom properties: taking personalization a step further

Besides having a name and message, your errors are spoilt for choice when it comes to custom properties. What's more, if you pay a visit to Mr. toString and convince him to change his ways, you can control how your error appears when printed. Suave error messages, anyone? 😎

Nostalgia trip: function constructors & prototypical inheritance

Long before we had ES6 class syntax, we depended on function constructors and prototypal inheritance for creating exceptions. These are tools are not to be underestimated.💼

Tailoring exceptions to fit your app

Domain-specific exceptions: the right tool for the job

Custom exception types let you micromanage how different kinds of errors are handled down to the minutest detail. Add some spice with some domain-specific attributes on top of the familiar name and message.

this.htmlMessage = `<p>I'm sorry Dave, I can't let you do that: ${message}</p>`; this.level = "critical";

Catching like a pro: typed exception handling

The freedom to catch only specific types of exceptions is an underrated JavaScript power move. Caught the wrong error? Send it back and tell it, "Not in my house!" 🏀

Real world applications for custom exceptions

  • Hold the door! Check inputs before they walk in
  • Business rules: the unwelcoming bouncers of the corporate world
  • Dealing with third-party APIs: when you need to match their specific brand of quirkiness 😅

Exception extras

Exception handling in modules

Pack your custom exceptions into a module or class, then export them for a surprise drop-in into any file that needs them. It's like a pop-up shop, but for error handling! 🛍️

Exceptional hierarchies

Create an entire family tree of error types by extending your custom exceptions. It's like a soap opera, but with more exceptions and less drama. 🍿

Catch me asynchronously if you can

Error handling in async code

Considering promises and async/await, a sound grasp of asynchronous error handling is non-negotiable. Thrown exceptions need catching or they'll disappear, like a ninja in the night 🌒.

async function fetchData() { if (unsuccessfulCondition) { throw new CustomError("A wild Error appeared!"); } }

Exceptional testing

In testing, custom exceptions prove crucial. Make assertions laser-precise — expect certain kinds of errors, not just any will do.

expect(() => riskyOperation()).toThrow(CustomError);

Messages your team will thank you for

Good error messages, like good docs, save hours of debugging frustration. Design messages that developers will want to read. Red roses for Valentine’s day is a cliché, so are cryptic error messages on a developer’s console. 🌹😊