Home > Blockchain >  In an NodeJS Express route, when an Error is thrown with a certain message, where is this message in
In an NodeJS Express route, when an Error is thrown with a certain message, where is this message in

Time:11-27

I have the following code:

index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  throw new Error("TESTING WHERE MY ERROR MESSAGE GOES IN MY RESPONSE...");
});

module.exports = router;

And the following test with Jest Supertest:

error.test.js

const app = require("../app");
const supertest = require("supertest");

describe("What is the relation between an Error object throuwn and in the corresponding response?", () => {

    test("Error", async () => {

        await supertest(app)
            .get("/")
            .then(async (res) => {
                console.log(res);
                expect(1).toBe(1);
            });
    });

});

I've been searching in this res object for the message I used to throw the Error.

I am assuming there is a relation, in this case, between the Error thrown and the res caught in the test.

Where is res I may find my error message?

CodePudding user response:

You should have an errorHandler. Simply throwing the error in backend will cause the backend to stop if there is no error handler defined. Another option could be instead of throwing error in your route, you can send

res.status(500).json({message:'TESTING WHERE MY ERROR MESSAGE GOES IN MY RESPONSE...'})

If you want to go with errorHandler approach, then you have to define the error handler and add it at the end of your app like this app.use(errorHandler).

Express has a great documentation for error handling

  • Related