ExpressJS: How to throw custom errors

The problem

Throwing readable custom errors is one of the most critical steps in the development of web applications. The communication between services must be clear and straight to the point.

The tool

Express middlewares whe…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Felipe Leao

The problem

  • Throwing readable custom errors is one of the most critical steps in the development of web applications. The communication between services must be clear and straight to the point.

The tool

  • Express middlewares when building NodeJS applications

The Solution:

  • Build an express middleware to throw custom responses error statusCode and messages

  • Our example will utilize a simple API built with ExpressJS and Prisma as an ORM

// app.ts


import express, { Request, Response, NextFunction } from 'express'
import 'express-async-errors'
import { router } from './routes'
import cors from 'cors'

const app = express()
app.use(express.json())
app.use(cors())
app.use(router)

app.use((err: {err: Error, statusCode: number, message: string}, _req: Request, res: Response, _next: NextFunction) => {
  if (err.err && err.err instanceof Error) {
    return res.status(err.statusCode).json({
      message: err.message,
      status: 'error'
    })
  }
  return res.status(500).json({
    status: 'error',
    message: 'Internal server error'
  })
})

export { app }
  • In addition, we can also define how our error response will be displayed to our clients. Here you can choose to show whatever you want and whatever you feel is pertinent for the client to see.

// lib/error

const builder = ({ statusCode, message }: {statusCode: number, message: string}) => {
  return {
    err: new Error(),
    statusCode,
    message
  }
}

export const error = { builder }

  • The object error should be thrown in the following manner

// src/services/userService.ts

import { error } from '../../lib/error'
import prismaClient from '../database/client'
import { IUser } from '../types/IUser'

interface ICreateUserRequest {
  name: string
  email: string
  password: string
}
const create = async ({ name, email, password }: ICreateUserRequest): Promise<IUser> => {
  if (!email) {
    throw error.builder({ statusCode: 422, message: 'Email not provided' })
  }

  if (await prismaClient.user.findFirst({ where: { email } })) {
    throw error.builder({ statusCode: 412, message: 'Email already taken' })
  }

  const user = await prismaClient.user.create({
    data: { name, email, password }
  })

  return user
}

export const userService = {create}

  • receiving and validating our custom statusCode and error message jest

insomnia


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Felipe Leao


Print Share Comment Cite Upload Translate Updates
APA

Felipe Leao | Sciencx (2022-11-02T00:53:03+00:00) ExpressJS: How to throw custom errors. Retrieved from https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/

MLA
" » ExpressJS: How to throw custom errors." Felipe Leao | Sciencx - Wednesday November 2, 2022, https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/
HARVARD
Felipe Leao | Sciencx Wednesday November 2, 2022 » ExpressJS: How to throw custom errors., viewed ,<https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/>
VANCOUVER
Felipe Leao | Sciencx - » ExpressJS: How to throw custom errors. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/
CHICAGO
" » ExpressJS: How to throw custom errors." Felipe Leao | Sciencx - Accessed . https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/
IEEE
" » ExpressJS: How to throw custom errors." Felipe Leao | Sciencx [Online]. Available: https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/. [Accessed: ]
rf:citation
» ExpressJS: How to throw custom errors | Felipe Leao | Sciencx | https://www.scien.cx/2022/11/02/expressjs-how-to-throw-custom-errors/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.