What is the correct approach to managing Sequelize validation errors effectively?

I am working on a basic REST API using Typescript, Koa, and Sequelize.

If the client sends an invalid PUT request with empty fields for "title" or "author", it currently returns a 500 error. I would prefer to respond with a '400 Bad Request' instead of that. How can I achieve this?

Below is part of the controller code:

import {JsonController, Get, Post, Put, Body, Param} from "routing-controllers";
import {Book} from "../models/Book";

@JsonController("/api")
export class BookController {
    @Put("/books/:id")
    async update(@Param("id") id: number, @Body() book: Book) {
        return await Book.update(book, {where: {id: id}});
    }
}

This snippet shows how Sequelize validators are used as decorators in the model:

import {Table, Column, NotEmpty, Equals, Model, HasMany} from 'sequelize-typescript';

@Table({tableName: 'Books'})
export class Book extends Model<Book> {

    @NotEmpty
    @Column
    title: string;

    @NotEmpty
    @Column
    author: string;
}

The current error message displayed is:

"message": "Validation error: Validation notEmpty on title failed,\nValidation error: Validation notEmpty on author failed"

Answer №1

Consider implementing the ValidationFailed hook

import {ValidationFailed} from 'sequelize-typescript'

@ValidationFailed
static afterValidateHook(instance, options, error) {
  throw new CustomErrorWithStatus(error.message, 400);
}

Where CustomErrorWithStatus is

class CustomErrorWithStatus extends Error {
  status: number;

  constructor(message, status = 400) {
    super(message);
    this.status = status;
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify information on the user interface without the need to refresh the page

Is there a way to update data on the UI without having to refresh the screen in a web application built with Node.js? I'm looking to make only specific changes on the screen. Additionally, how can I ensure that the data displayed on the screen is upda ...

Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev. However, an issue arises every time Next.js boots up, displaying the following error: FetchError: request to https://fonts.gstatic.com/ ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

The curious case of Node.JS: The mysterious behaviour of await not waiting

I am currently utilizing a lambda function within AWS to perform certain tasks, and it is essential for the function to retrieve some data from the AWS SSM resource in order to carry out its operations effectively. However, I am encountering difficulties i ...

Escape a "for" loop from within a callback function in Node.js

My objective with the code snippet below is to exit FOR LOOP B and continue with FOR LOOP A by utilizing a callback function. for(var a of arrA) { // ... // ... for(var b of arrB) { // ... // ... PartService.getPart(a ...

How can Vue define the relationship on the client-side when submitting a post belonging to the current user?

Currently, I am developing an application using Node.js, specifically Express server-side and Vue client-side, with SQLite + Sequelize for managing the database. One of the features of this app is that a user can create a post. While this functionality ex ...

Passport appears to be experiencing amnesia when it comes to remembering the user

After extensive research online, I have yet to find a solution to my issue. Therefore, I am reaching out here for assistance. I am currently working on implementing sessions with Passport. The registration and login functionalities are functioning properl ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

What are the different ways you can utilize the `Buffer` feature within Electron?

When attempting to implement gray-matter in an electron application, I encountered the error message utils.js:36 Uncaught ReferenceError: Buffer is not defined. Is there a method or workaround available to utilize Buffer within electron? ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

What is the process for configuring environmental variables within my client-side code?

Is there a reliable method to set a different key based on whether we are in development or production environments when working with client-side programs that lack an inherent runtime environment? Appreciate any suggestions! ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even con ...