Skip to content

Instantly share code, notes, and snippets.

@paul-vd
Created June 29, 2021 14:50
Show Gist options
  • Save paul-vd/5c542d3f809e76204031e141f9024fdb to your computer and use it in GitHub Desktop.
Save paul-vd/5c542d3f809e76204031e141f9024fdb to your computer and use it in GitHub Desktop.
Example Error Instances
'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
}
}
@paul-vd
Copy link
Author

paul-vd commented Jun 29, 2021

you can then query errors, for example;

   try {
      const data = await getData()
      return res.jsend.success(data )
    } catch (error) {
      logger.apiError(error)
      if (error instanceof UserFacingError) {
        return res.status(error.code).send(error)
      }
      return res.status(500).send('SOME GENERIC ERROR MESSAGE')
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment