DEV Community

Luka Vidaković
Luka Vidaković

Posted on

From custom error types to a custom error subtype

Previously we defined our most basic custom error class that extends the Javascript's Error prototype:

class MyError extends Error {
  constructor(message) {
    super(message)
    this.name = 'MyError'
    Error.captureStackTrace(this, MyError)
  }
}
Enter fullscreen mode Exit fullscreen mode

Now let's create an error subtype that will be used to indicate certain failures for a few well known HTTP response states. MyError class and error name will be renamed to a more generic name that goes along with the context of an HTTP server — HttpError.

To keep it short, we'll pick only 3 commonly encountered HTTP status codes and create custom errors for them.

constants/httpResponseCodes.js

module.exports = {
    BAD_REQUEST: 400,
    NOT_FOUND: 404,
    INTERNAL_SERVER_ERROR: 500,
}
Enter fullscreen mode Exit fullscreen mode

utils/errors.js

const responseCodes = require('../constants/httpResponseCodes.js')

class HttpError extends Error {
  constructor({ message, name, statusCode, data }) {
    super(message);
    this.name = name;
    this.statusCode = statusCode;
    this.data = data;
    Error.captureStackTrace(this, HttpError);
  }
}

class HttpBadRequest extends HttpError {
  constructor(message = 'Bad request', data) {
    super({
      message,
      name: "HttpBadRequest",
      statusCode: responseCodes.BAD_REQUEST,
      data
    });
  }
}

class HttpNotFound extends HttpError {
  constructor(message = 'Not Found', data) {
    super({
      message,
      name: "HttpNotFound",
      statusCode: responseCodes.NOT_FOUND,
      data
    });
  }
}

class HttpInternalServerError extends HttpError {
  constructor(message = 'Internal server error', data) {
    super({
      message,
      name: "HttpInternalServerError",
      statusCode: responseCodes.INTERNAL_SERVER_ERROR,
      data
    });
  }
}

module.exports = {
  HttpError,
  HttpBadRequest,
  HttpNotFound,
  HttpInternalServerError
}
Enter fullscreen mode Exit fullscreen mode

We now have our custom error types and their subtype(HttpError), that will allow us to handle all of them in a generic way in the following post. A lot of code could be stripped down by using prototypal inheritance at a lower level. But it's not such a problem even if so verbose, it's very easy to follow through and the code probably won't change much once it's finished. There are libraries out there that make creating custom errors easier, but I like to have such a crucial part of the service completely independent and understandable.

Top comments (0)