npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

trycatch-alter

v1.3.0

Published

A package that provides an alternative approach to writing multiple try-catch blocks,along with handling API responses in a backend program.

Downloads

5

Readme

Introduction

This package is designed to simplify error handling in backend projects by replacing multiple instances of try-catch blocks with just one function asyncHandler. It also includes an API response utility (ApiResponse) that simplifies the process of sending responses to clients. With the API-Response function, you only need to provide the status code and message, and optionally, the data you want to send. Additionally, the package provides an API-Error function (ApiError) to help you manage and handle error messages more efficiently.

Getting started

Installation This package can be installed using npm

npm i trycatch-alter

Importing functions

import asyncHandler function

const { asyncHandler } =  require('trycatch-alter');

import ApiResponse function

const { ApiResponse } =  require('trycatch-alter');

import ApiError

const { ApiError } =  require('trycatch-alter');

Or you import all function in one line

const { ApiError, ApiResponse, asyncHandler } =  require('trycatch-alter');

How to use this function

For asyncHandler

exports.example = asyncHandler(async (req, res) => {
    // Write your backend logic here
    // No need to write a try-catch block; asyncHandler will handle errors
});

For Api Response

new ApiResponse(statusCode, Data, "your message for response");

For Api Error

throw  new ApiError(statusCode, "your message for the error");

Example

Example 1

Now, We understand how to use this npm library through a simple example, like creating a todo app, where I can demonstrate how to use it in my createTodo file.

// Import the Todo model  
const  Todo = require("../models/Todo"); 

// Import necessary functions from the trycatch-alter library  
const { ApiError, ApiResponse, asyncHandler } = require('trycatch-alter');

// Define the route handler for creating a new todo 
exports.createTodo = asyncHandler(async (req, res) => {
 
    // Extract the title and description from the request body  
    const { title, description } = req.body; 
    
    // Check if both title and description are provided  
    if (!title || !description) { 
	    throw  new  ApiError(400, "Please provide both a title and a description"); 
	}
	
	// Create a new todo object and insert it into the database
	const todo = await Todo.create({ title, description });
	
	// Send a JSON response with a success message
	res.status(200)
	.json(new ApiResponse(200, todo, "Todo created successfully"));
	});

Example 2

// Import the Todo model and necessary functions from the trycatch-alter library
const Todo = require("../models/Todo");
const { ApiError, ApiResponse, asyncHandler } = require('trycatch-alter');

    // Route handler to fetch all todo items
    exports.getTodo = asyncHandler(async (req, res) => {
	    
	    // Fetch all todo items from the database
	    const todos = await Todo.find({});

	    // Respond with the fetched todo items
	    res.status(200).json(
	        new ApiResponse(200, todos, "All todo data successfully fetched")
	        );
	});


    // Route handler to fetch a todo item by ID
    exports.getTodoById = asyncHandler(async (req, res) => {
	    
	    // Extract the todo item ID from the request parameters
	    const id = req.params.id;

	    // Find the todo item in the database based on the ID
	    const todo = await Todo.findById({ _id: id });

	    // If no todo item is found with the given ID, throw an error
	    if (!todo) {
	        throw new ApiError(404, "No data found with the given ID");
	    }

	    // Respond with the fetched todo item
	    res.status(200).json(
	        new ApiResponse(200, todo, `Todo item with ID ${id} successfully fetched`)
	    );
    });

License

This project is licensed under the MIT license.

Disclaimer

Please ensure that you follow the correct installation and usage instructions for this library. Improper usage may lead to unexpected behavior or errors. Always refer to the official documentation for the most up-to-date information.

Keywords

  1. trycatch-alter
  2. ApiResponse
  3. ApiError