Skip to content

Instantly share code, notes, and snippets.

@paul-vd
Created June 29, 2021 14:50

Revisions

  1. paul-vd created this gist Jun 29, 2021.
    109 changes: 109 additions & 0 deletions error-instance.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,109 @@
    'use strict'

    // Here is the base error classes to extend from

    export class ApplicationError extends Error {
    get name() {
    return this.constructor.name
    }
    }

    export class DatabaseError extends ApplicationError {
    get code() {
    return 500
    }
    }

    export class UserFacingError extends ApplicationError {
    get code() {
    return 400
    }
    }

    import { UserFacingError } from './base-errors'

    /** UserFacingError - 400 */
    export class BadRequestError extends UserFacingError {
    constructor(message, options = {}) {
    super(message)

    // You can attach relevant information to the error instance
    // (e.g.. the username)

    for (const [key, value] of Object.entries(options)) {
    this[key] = value
    }
    }

    get code() {
    return 400
    }
    }

    /** UserFacingError - 401 */
    export class NotAuthorisedError extends UserFacingError {
    constructor(message, options = {}) {
    super(message)

    // You can attach relevant information to the error instance
    // (e.g.. the username)

    for (const [key, value] of Object.entries(options)) {
    this[key] = value
    }
    }
    get code() {
    return 401
    }
    }

    /** UserFacingError - 403 */
    export class ForbiddenError extends UserFacingError {
    constructor(message, options = {}) {
    super(message)

    // You can attach relevant information to the error instance
    // (e.g.. the username)

    for (const [key, value] of Object.entries(options)) {
    this[key] = value
    }
    }
    get code() {
    return 403
    }
    }

    /** UserFacingError - 404 */
    export class NotFoundError extends UserFacingError {
    constructor(message, options = {}) {
    super(message)

    // You can attach relevant information to the error instance
    // (e.g.. the username)

    for (const [key, value] of Object.entries(options)) {
    this[key] = value
    }
    }
    get code() {
    return 404
    }
    }

    /** UserFacingError - 409 */
    export class ConflictError extends UserFacingError {
    constructor(message, options = {}) {
    super(message)

    // You can attach relevant information to the error instance
    // (e.g.. the username)

    for (const [key, value] of Object.entries(options)) {
    this[key] = value
    }
    }
    get code() {
    return 409
    }
    }