🚨 Shai-Hulud Strikes Again:834 Packages Compromised.Technical Analysis →
Socket
Book a DemoInstallSign in
Socket

express-http-handler

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-http-handler

Express error handler and http status code and validate request

latest
Source
npmnpm
Version
1.0.2
Version published
Maintainers
1
Created
Source

express-http-handler

Express error handler and http status code and validate request

Install

npm install express-http-handler

Use

import express, { Request, Response } from 'express';
import {
  errorHandler,
  HttpError,
  HttpStatus,
  notFoundHandler,
  validateRequest,
} from 'express-http-handler';
import { object, string } from 'yup';

const app = expess();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get('/test', (req: Request, res: Response) => {
  try {
    const somethingWrong = true;

    if (somethingWrong) {
      throw new HttpError('Something error', HttpStatus.BadRequest);
    }
    // ...
  } catch (error: any) {
    HttpError.json(res, error);
  }
});

const userLoginSchema = object({
  body: object({
    email: string().email('Email is invalid').required('Email is required'),
    password: string().required('Password is required'),
  }),
  // query: ,
  // params: ,
  // file: ,
});

app.post(
  '/login',
  validateRequest(userLoginSchema),
  (req: Request, res: Response) => {
    try {
      const somethingWrong = true;

      if (somethingWrong) {
        throw new HttpError('Something error', HttpStatus.BadRequest);
      }
      // ...
    } catch (error: any) {
      HttpError.json(res, error);
    }
  }
);

//At the end of middleware
app.use(notFoundHandler);
app.use(errorHandler);

app.listen(5000, () => {
  console.log('server running on port 5000');
});

Credit and Thanks

Thanks to RWOverdijk for compiling the http status code.

Keywords

express

FAQs

Package last updated on 28 Feb 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts