What could be causing the catch() block to not execute in Objection.js queries, with the then() method always running and returning either 0 or 1 as a result?

When executing a query using Objection.js, the result of the query will be passed to the then() block as either 0 or 1 depending on its success or failure. Instead of handling errors in the catch block, I find myself checking falsey values. Is there a better way to approach this situation?

const editIndustry = async (req, res, next) => {
    const industry = await Industry.query().findById(req.params.industryId);

    if (!industry) {
        return res.status(404).json({
            error: 'NotFoundError',
            message: `industry not found`,
        });
    }
    await industry
        .$query()
        .patch({ ...req.body })
        .then(result => console.log(result, 'then() block'))
        // never runs
        .catch(err => {
            console.log(err);
            next(err);
        });
};
Server is running and listening on port 3000.
The then() block executed successfully once.

Answer №1

Your code is functioning as intended. The reason why it's not entering the catch block is because there is no error occurring. When using patch, it does not return the row but instead returns the number of rows that were changed (refer to the documentation).

The method you may be looking for is patchAndFetchById (see documentation). If you want to handle a 404 error, you can use the throwIfNotFound modifier. This will throw an error if the record is not found in the database, allowing you to catch and properly respond with a 404 status code. Otherwise, you would return a 500 status code. To do this, you will need to import NotFoundError from objection.

const { NotFoundError } = require('objection');
const Industry = require('<myIndustryModelLocation>');

const editIndustry = (req, res) => {
  try {

    return Industry
        .query()
        .patchAndFetchById(req.params.industryId, { ...req.body })
        .throwIfNotFound();

  } catch (err) {

    if(err instanceof NotFoundError) {
      return res.status(404).json({
        error: 'NotFoundError',
        message: `industry not found`,
      });
    }

    return res.status(500);
  }
};

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

Learn how to smoothly transfer a URL from JavaScript to HTML and initiate the download process

I created a website that solely relies on HTML5, CSS and JavaScript to function. The core functionality of this website involves utilizing YouTube URLs. I have stored the URL of a specific YouTube video as a variable, now I am looking for a way to transfer ...

Automated bonsai cataloging

In my express app hosted on Heroku, I am utilizing MongoDb for storage. To improve search capabilities within some of my MongoDb collections, I want to integrate ElasticSearch through the Bonsai Heroku add-on found at Bonsai. However, the Bonsai faq stat ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Retrieving user information from Firebase with Promise instead of Observable

In my React project, I successfully implemented the Observer pattern to retrieve user data from Firebase. This approach made perfect sense and here is a snippet of the code where I utilized the observer pattern: unsubscribeFromAuth = null; componentDidMou ...

What is the best way to showcase a photo selected using an HTML input within a div container?

My goal is to select a photo from a folder and display it on a webpage, but I have struggled to find a working solution. Can this be achieved using just basic HTML, CSS, and JS? I am new to web development, so please forgive me for any beginner questions. ...

Generating observables from form submission event

Note: I am completely new to Angular and RXJS. Currently, I am working on a simple form where I want to create an observable. The goal is to listen for submit events and update a value within the component. However, I keep encountering an error message sa ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

Unlock the power of viewing numerous inputs simultaneously

Seeking guidance on how to allow users to preview images before uploading them. Currently, my code successfully previews images for one input field, but I am facing challenges when trying to add multiple pairs of inputs and images. How can I implement mul ...

The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block. However, in my code, something appears to be off as it doesn't behave that way: var noDupes = false; // se ...

Include jQuery, jQuery UI, and plugins seamlessly to avoid any version conflicts

My goal is to inject my custom code into a webpage using a bookmarklet. This code requires jQuery, jQuery UI, and additional plugins to be included on the page. I'm aware of the noConflict function, but I have concerns about potential conflicts if ot ...

An error has occurred due to a connection timeout with the net.Socket

I have been attempting to send text to my network printer using a tcp connection. function print(buf2){ var printer = new net.Socket(); printer.connect(printer_port, printer_name, function() { console.log('Connected'); printe ...

Executing a task prior to a redirect using passport.authenticate

I have implemented WebDevSimplified's login script and so far it's functioning correctly. However, I have encountered an issue where I would like to execute a specific function before the redirection takes place after a successful login. Once th ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Error Message: Unable to Locate File in NestJSExplanation: The specified file could not

I'm encountering an issue with my nestJS app not being able to read my cert secret file or even a basic text file. The error message I'm receiving is: ERROR [ExceptionsHandler] ENOENT: no such file or directory Here's the code snippet whe ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

Invoke an AngularJS directive from a controller when clicked

Hey there! I'm currently utilizing the tg-dynamic-directive to loop through a JSON file and display the tree structure shown in the attached image. https://i.sstatic.net/Ph6Cs.png One major issue I'm facing is performance degradation when the " ...

Display a modal upon successful validation of a form

As a newcomer to JavaScript and Bootstrap, I have a specific requirement: 1. When a user clicks the submit button, 2. The form needs to be validated using the entry_check() function. 3. Upon successful validation of the form, a Bootstrap modal should be op ...

Stop Element-UI from automatically applying the list-item style to li elements

I have a list of data elements that I am rendering in the following way: <ul> <li v-for="el in elements"> {{el.data}} </li> </ul> Here's how I style it in my .css file: ul { list-style-type: none; padd ...

"The JavaScript code included in the index.html file is not functioning as expected when called in the main.js file within a

Here is the index.html code for a simple VueJS app that includes a widget from netvibes.com. The widget code is added in the html file and functioning properly. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC " ...

Creating HTML elements using JavaScript compared to importing an HTML fileIn JavaScript,

I am currently in the process of building a website that is entirely driven by JavaScript. Aside from the index page, I do not use any HTML pages at all. Instead, I fetch JSON data for every query and then dynamically generate HTML within the JavaScript to ...