Reducing code repetition and creating custom error handling in Typescript back-end operations

I have implemented data validation and sanitization in my Branch class, but I am concerned about the repetition in my code. I feel like I may be using custom errors excessively by creating one for each situation.

I would appreciate some suggestions on how to adhere to the DRY principle in this code and create reusable custom errors.

import {Column, Entity, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
import {SystemModule} from "../../enums/SystemModule.enum";
import {Environment} from "../Environment.entity";
import {ZipCode} from "../../value-objects/ZipCode/ZipCode.value-object";
import {Cnpj} from "../../value-objects/Cnpj/Cnpj.value-object";
import {NameLengthCannotBeZeroException} from "./exceptions/NameLengthCannotBeZero.exception";
import {NameLengthCannotBeAbove200Exception} from "./exceptions/NameLengthCannotBeAbove200.exception";
// Other exception imports...

@Entity("branches")
export class Branch {

    // Class properties here...

    private static sanitizeAndValidateProperty(value: string | number | null, maxLength: number, exceptionType: any) {
        const sanitizedValue = String(value).split("\n")[0]
            .replace(/^[\r\t\f ]+|[\r\t\f ]+$/g, "")
            .replace(/[\t\f ]+/g, " ");
        
        if (sanitizedValue.length > maxLength) {
            throw new exceptionType();
        }
        
        return sanitizedValue;
    }

    // Methods to sanitize and validate different entity properties...
}

Answer №1

I am seeking suggestions on how to apply the DRY principle in my code and create reusable custom errors.

The level of granularity may vary, but typically you would define different types of exceptions for various categories of potential issues (such as identification/authentication errors, domain/data errors, external service errors, etc.), with possible subclasses if needed. Each exception could include an error code that corresponds to a message stored in a table, similar to how HTTP or database errors are handled.

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

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...

TypeScript - Defining the return type of a function that creates a new object instance

Currently, I have a TypeScript function that is responsible for returning a fresh instance of Elasticsearch: public getClient(): any { return new Elasticsearch.Client({ host: ['url', ':', 'port'].join('' ...

Learn how to set up browser targeting using differential loading in Angular 10, specifically for es2016 or newer versions

Seeking advice on JS target output for compiled Angular when utilizing differential loading. By default, Angular compiles TypeScript down to ES5 and ES2015, with browsers using either depending on their capabilities. In order to stay current, I've b ...

I'm struggling to figure out the age calculation in my Angular 2 code. Every time I try to run it,

Can anyone assist me with calculating age from a given date in Angular? I have written the following code but I keep getting undefined in the expected field. This is Component 1 import { Component, OnInit, Input } from '@angular/core'; ...

Angular two - Communication between parent and children components using a shared service

I am currently working on establishing communication between child components, but according to the documentation, I need to utilize services for this purpose. However, I am facing challenges in accessing service information. When I try to assign the retur ...

When trying to reload Angular 8 pages, encountering an error that reads "Cannot GET /login" and also receiving a notification stating the image '/favicon.ico' cannot be loaded due to a violation of

Encountering an issue with the error message "Cannot GET login/" appearing on the page body of my latest Angular 8 app. Despite attempting various solutions found on forums, I have been unable to resolve this error. Any suggestions or advice would be great ...

What is the best way to access a private class variable within the sockent.on function in Angular?

export class AppComponent { title = 'my-app'; constructor(private notifyService : NotificationService) {} ngOnInit() { socket.on("laravel_database_chat:test", function(message){ //I AM ATTEMPTING TO INVOKE THE NOTIF ...

Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated. Below is the class in my SCSS file: .form-validation.invalid { border: 2px solid red } In my ts file, there's a variable named isEmailValid. When this variable is set to ...

How can I ensure that a list displaying data from an API is properly rendered in React.js using Vitest?

I have a component that displays a list fetched from a REST API using a useEffect hook without any dependencies. The fetched data is then stored in state. Here is the code snippet: import { useEffect, useState } from 'react'; import { fetchAllMed ...

Unlock the potential of Power BI with this step-by-step guide on enhancing the Circle Card visual by incorporating unique formatting

Power BI Tutorial: Adding Formatting Options to the Circle Card Visual After completing step 8, I copied the code into my VS Code and encountered 2 error messages: Error message: "import VisualSettings - Module '"./settings"' has no e ...

How to showcase the date in a unique format using Angular

Does anyone know of a JavaScript ES7 method that can convert the output of new Date() into the format shown below? If there isn't a built-in method, I am willing to manually parse or find/replace it myself. 2020-06-30 07.49.28 I would like the da ...

The importance of maintaining separation of concerns within Laravel controllers

For the past week, I've been immersed in a php project using Laravel and trying to ensure that I'm adhering to best practices. I find Resource controllers and CRUD to be very logical and have decided to adopt this approach. However, when dealing ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

Looping through Observable with an Array using *ngFor in Angular

My Angular App is having trouble displaying all the items of a device due to issues with iterating through an observable array. The error message I am currently encountering is as follows: Error: Cannot find a differ supporting object '[object Obje ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

Angular's observable data fail to show on the screen

I am facing an issue with passing the data of an Observable fetched via an API request to a component variable for display. I have been trying but unable to make it work successfully. Any assistance would be greatly appreciated. Here is my code. Thank you. ...

Using Datatable.net with Angular 6 for Change Monitoring

I've been encountering several issues with the custom datatable component that I created. One specific problem is that when I delete a row from my datatable, not only does the row disappear, but also the pagination functionality and other features st ...

Where can I locate htmlWebpackPlugin.options.title in a Vue CLI 3 project or how can I configure it?

After creating my webpage using vue cli 3, I decided to add a title. Upon examining the public/index.html file, I discovered the code snippet <title><%= htmlWebpackPlugin.options.title %></title>. Can you guide me on how to change and cu ...

What is the best way to specify parameter names and types for a TypeScript function that can take either one or two arguments?

Looking to create a function with two different calling options: function visit(url: string, options: Partial<VisitOptions>): void function visit(options: Partial<VisitOptions> & {url:string}): void I'm exploring the most effective w ...

The Mui datepicker displays the day and month in reverse order

Do you have trouble with date search filter using the mui datepicker component? It seems that when entering a date in the input and clicking on search, the day gets swapped with the month. For instance, if you input 03/05/2022, it returns Sat Mar 05 2022 ...