Tips for managing the visibility of raised errors in Firebase functions

Utilizing async/await in my firebase functions poses the challenge of managing potential errors with each call. I am unsure of the best approach to handle catching these errors. Wrapping every call in a try/catch block seems cumbersome given the use of the await syntax.

Allowing my awaits to throw errors results in firebase-functions catching and logging them, which is beneficial. However, I want to prevent these errors from being sent back to the client.

Is there a way to capture and control all thrown errors to customize the returned response?

Answer №1

Challenge. Dealing with a large try/catch block:

module.exports = async (req, res) => {
  // Obtain the data from the request
  const input1 = req.body.input1
  const input2 = req.body.input2

  try {
    // Initially await for file information
    const fileInfo = await db.getFileInfo(input2)

    // Perform some synchronous operations
    const tempFilePath = generateUniqueTempFilePath(fileInfo)

    // Further asynchronous actions
    await storage.download(input1, tempFilePath)
    const checkinResult = await db.checkin(tempFilePath, data)

    const result = { checkinResult, fileInfo }
    res.json(result)
  } catch (err) {
    res.status(500).send(err.message)
  }
}

One approach is to encapsulate all await calls and related logic in a separate function, centralizing the try/catch block within the endpoint method.

Illustration. Minimal try/catch and a dedicated function:

const service = require('./serviceA')

module.exports = async (req, res) => {
  // Obtain the data from the request
  const input1 = req.body.input1
  const input2 = req.body.input2

  // Execute asynchronous code in a single call
  var result = undefined
  try {
    result = await service.perform(input1, input2)
  } catch (err) {
    res.status(500).send(err.message)
    return
  }
  res.json(result)
}

and

async function perform (input1, input2) {
  // Initial async operation (no try/catch needed!)
  const fileInfo = await db.getFileInfo(input2)

  // Perform some synchronous work
  const tempFilePath = generateUniqueTempFilePath(fileInfo)

  // Additional async tasks (ensure they throw errors with appropriate messages!)
  await storage.download(input1, tempFilePath)
  const checkinResult = await db.checkin(tempFilePath, data)

  return { checkinResult, fileInfo }
}

module.exports = { perform }

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

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

Coverage of code in Angular2 using Qunit

Is there a reliable code coverage measurement tool or framework that can easily be integrated to assess the code coverage of Angular2-TypeScript code with QUnit tests? I have come across some frameworks like remap-istanbul, blanket.js etc., but these fram ...

My component is missing the ChangeDetectorRef in Nativescript

I am attempting to automatically update an array within a Listview by utilizing ChangeDetectorRef in the following way: import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef } from "@angular/core"; @Component({ selector: "regi ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

React Component not displaying properly when used inside a map iteration

I am currently working on rendering multiple components using the .map method on an array with specific content. Although I can't find any errors in the console, the component is not appearing in the DOM as expected. I attempted to set subHeader to nu ...

Using Typescript and Next.js to handle error messages returned from Axios responses

My Next.js application makes an API call to validate a registration form. The server returns error messages in the following format: {"message":"The given data was invalid.","errors":{"email":["The email has alr ...

Remember to always call "done()" in Typescript + Mocha/Chai when dealing with async tests and hooks. Additionally, when returning a Promise, make sure it resolves correctly

It seems like I'm facing an old issue that I just can't seem to resolve, despite trying everything in my power. The error message reads: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Pro ...

Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript? I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected. Below is the code snippet I ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

How does the type of the original array influence the inferred types of the destructured array values?

let arr = [7, "hello", true]; let [a, ...bc] = arr; typeof bc : (string | number | boolean)[] why bc type is (string | number | boolean) expect: because bc = ["hello", true], so bc type should be (string | boolean)[] ...

Submitting Data in Ionic 3 using Http Post and Storing in Sqlite with Angular 4

I am facing an issue while trying to post an array of contacts on a WebService. When I send the array, the data appears as NULL in the WebService response. I am confused about how to use Let params{} The error message shows "object undefined". Addition ...

What sets npm start apart from firebase serve in terms of functionality and usage?

I have developed a new app that interacts with Firebase. The Firebase API has provided instructions for testing the application using commands like firebase serve and firebase deploy. When running firebase serve, a local server instance is created at local ...

Identifying the specific @Input that has changed in ngOnChanges

I am currently utilizing Angular 2. At the moment, I have two @input variables named aa and bb. My objective is: When aa changes, perform a specific action. When bb changes, execute a different action. How can I identify which @Input has changed within ...

Organizing the AuthGuard(canActivate) and AuthService code in Angular 2

After working on my current code, I have encountered an issue when routing to a page with the canActivate method. I was able to retrieve authentication data from the server using the following setup auth.guard.ts (version 1) import { CanActivate, Activat ...

In TypeScript, fetch JSON data from a URL and gain access to an array of JSON objects

I'm struggling to find a solution and implement it in the correct format. An API returns a JSON file to me via a URL. The format is as follows: {"success":true, "data":[ { "loadTimestamp":"2022-07-20T ...