Express ошибка 500

Building a web app or API with Express JS is mainly done for high-quality error handling. Error handling is one of the most underlooked yet important aspects of creating good code for your end users. In this article, we will discuss the Express JS error handling best practices and help you manage errors efficiently.

How Express JS error handling works

Expresses built-in error handling

Express JS performs the basic error handling task by default. When writing synchronous code Express will catch your errors and automatically create a 500 response with the error message.

app.get("/", (req, res) => {
	throw new Error("My error message here.");
})

The response will look something like this.

Express js error handling.webp

Express JS error handling middleware

The problem

Although the method shown above will work for basic examples using synchronous code, however, asynchronous code is a whole different beast. When the following code is used, the app does not automatically handle errors and will crash.

app.get("/", async (req, res) => {
	throw new Error("My error message here.");
})

The reason behind this is when a request is handled under the hood, express runs a try-catch statement in an error handling middleware shown in the code below.

try {
       fn(req, res, next);
} catch (err) {
	 next(err);
}

If you have ever error handled using the asynchronous functions the issue should now be clear. When throwing an error in an async function, it returns a promise that has been rejected rather than directly calling throw in the try statement.

How do we solve this

The solution to this problem is to run the next function directly instead of throwing an error. This ensures that the error middleware is called with the error.

app.get("/", async (req, res) => {
	return next(new Error("My error message here."))
})

If you are using promise chaining you can also put the next function in the catch statement.

app.get("/", async (req, res) => {
	promise()
		.then(() => {
			// do a thing	
		})
		.catch(next)
})

Writing your middleware

When writing your app you may need some more logic to handle your errors such as error loggers and custom error messages to your client. An error middleware is a function that will include error, request, response, and the next function as parameters.

An example of a middleware is an error logger. In its simplest form, it will log the error to the console and then pass the error to the next middleware. Below is a simple example of how you may implement this.

const errorLogger = (err, req, res, next) => {
	console.error(err.stack);
	next(err);
}

To use the middleware you can pass it into the “app.use” method after that you can include your routes.

Note: this order is essential.

// use your routes in your app
app.use(routers)
// then use your middlewares
app.use(errorLogger)

Another middleware that you can also use is an error handler that controls the error sent to the client. This can be important if you want to respond with an error in a specific format and response type. The error handler middleware will be at the end of the middleware error chain since it has to be run after all other middleware.

const errorHandler = (err, req, res, next) => {
	const statusCode = err.statusCode ?? 500;

	return res.status(statusCode ?? 500).json({
		error: statusCode,
		message: err.message
	})
}

You can include this handler by using it in your app below the error logger handler in the code.

Custom Errors

Custom error types are very useful when you write specific functionality or include specific attributes such as status codes in your error.

class CustomError extends Error {
	constructor(reason) {
		this.name = this.constuctor.name;
		this.message = `Custom error occured due to ${reason}.`;
		this.statusCode = 500;
	}
}

Express JS error handling 404

You can catch all responses that are not sent by adding a middleware at the end of the chain with a request, response, and next parameters.

const notFoundHandler = (req, res, next) => {
res.status(404).json({
		error: 404,
		message: "Route not found."
	})
}

app.use(notFoundHandler);

If you have a custom error handler middleware you can alternatively create a custom error type with a status code of 404 and an appropriate message.

Real-world example

To understand how you can use these techniques in a real project it’s good to practice by creating an example project. In this example, we will show how you can create a book API using scalable error-handling techniques.

Creating our middleware

As mentioned in the previous section, we can create middleware to handle the errors. In this example, we will use 3 main error-handling middleware. This will include middleware for logging errors, handling errors, and handling 404 errors.

We will put the middleware in a directory “src/middlewares”.
First, we have an error logger. This is almost the same as in the previous example and is nothing fancy. You can also save the output in a file.

// "src/middlewares/errorLogger.js"

const errorLogger = (err, req, res, next) => {
	// logs error to console and then passes to next middleware
  console.error(err.stack);
  next(err);
}

module.exports = errorLogger;

Next, we have the error handler. This middleware will take an error with a message and potential status code and return it to the client in a JSON format. This will be the last middleware in the chain as it is always the last thing to run.

// "src/middlewares/errorHandler.js"

const errorHandler = (err, req, res, next) => {
	// if no status or message in error use default 500 code and message
	const statusCode = err.status ?? 500;
	const message = err.message || "Something went wrong.";

	// returns error status code and message
	return res.status(statusCode).json({
		error: statusCode,
		message: message
	})
}

module.exports = errorHandler;

The last error middleware is a 404 not found error handler. We can do this by passing an error with the status code 404 to the error handler. To do this we will need to create a custom error with the status code 404 and the message “Not found”. We can put all our custom errors in the directory “src/helper/errors”.

// "src/helpers/errors/NotFoundError.js"
class NotFoundError extends Error {
  constructor() {
    super();
    this.status = 404;
    this.message = "Not found."
  }
}

module.exports = NotFoundError;

The middleware can now simply pass an instance of a not found error to the error middleware.

// "src/middlewares/errorNotFound.js"

const NotFoundError  = require("../helpers/errors/NotFoundError")

const errorNotFound = (req, res, next) => next(new NotFoundError();

module.exports = errorNotFound;

To use these routes we can simply run the use method on the express app. In our app, we will also use the built-in express JSON middleware and the router at the address “/api”. Again, while creating this make sure the ordering is correct as the flow of the middleware is important.

const express = require("express");
const errorHandler = require("./middlewares/errorHandler");
const errorLogger = require("./middlewares/errorLogger");
const errorNotFound = require("./middlewares/errorNotFound");
const routes = require("./routes");

const app = express();

app.use(express.json());

app.use("/api", routes);

app.use(
  errorNotFound, 
  errorLogger, 
  errorHandler
);

module.exports = app;

The router

We put our router in the directory “src/routes”. Since we are only using one route in this example we will just put all the code in “src/routes/index.js” but it is best practice to put each route and controller into directories.

First, let us create the route with no Express JS error handling. We can use the “express.Router“ method to create a router and export it as the default value from the file.

const express = require("express");
const fs = require('fs');

const router = express.Router();

module.exports = router;

For this API we will create the route “/find”, which will take a post request with a JSON body containing a filename and title for the book. We will store JSON files in a “data” directory and read them with the inbuilt fs library in node js. The fs.readFile method takes the encoding and a callback with an error and data parameter in the file path.

fs.readFile(`data/${filename}.json`, 'utf8', (err, data) => {/*code*/})

In the callback, we will first parse the data as a JSON object. We can do this with the JSON.parse method as shown below.

const json = JSON.parse(data);

We now need to filter the data for books with a given title. We can use the filter method that you can call on arrays in JavaScript.

const books = json.books.filter(
  val => val.title.toLowerCase().includes(title.toLowerCase()));

Lastly, we return a response with a 200 status code and JSON object of the books.

return res.status(200).json({
  books
})

All together your file with no error handling should look as follows.

// "src/routes/index.js"

const express = require("express");
const fs = require('fs');

const router = express.Router();

router.post("/find", async (req, res, next) => {
  const {filename, title} = req.body;
    
  fs.readFile(`data/${filename}.json`, 'utf8', (err, data) => {
    const json = JSON.parse(data);

    const books = json.books.filter(
	    val => val.title.toLowerCase().includes(title.toLowerCase()));
	
	  return res.status(200).json({
      books
    })
  });
})

module.exports = router;

Now if we send a request with fields that won’t cause an error when we get a response that looks like the following.

Express js error handling best practices.webp

Adding errors

There are 3 main places in this code where we may want to add error handling. The first will be to validate that the body does include the required parameters. We could resolve this directly in the route by checking if the parameters exist. A better way to do this is by creating a function that returns a middleware to check on the existence of the required parameters. The reason we do this is that this functionality will likely be used all over the code in many routes.

First, we will create a new custom error in “helper/errors” called RequiredBodyError. This error will be in the fields that are not included in the constructor. It will then set the status code to 400 and set the message to “Request must include the fields: (names of fields)”. This is simply done in the example below.

class RequiredBodyError extends Error {
    constructor(notIncludedFields) {
        super();
        this.status = 400;
        this.message = `Request must include the fields: ${notIncludedFields.join(', ')}.`;
    }
}

module.exports = RequiredBodyError;

We have our custom error that will create the function which will eventually create the middleware. To do this we will take in an array called fields which are the required fields and then check if the body has all of the fields. If the body doesn’t have all the fields it will run the next error middleware with a RequiredBodyError with all the missing fields.

const RequiredBodyError = require("../helpers/RequiredBodyError");
const requiredFields = (fields) => {
  return (req, _res, next) => {
    const missingFields = [];
    const keys = Object.keys(req.body); // Included fields

		// Checks if every required field is in the body
    for(const field of fields)
      if(!keys.includes(field))
        missingFields.push(field)

		// If there are missing fields then run next error middleware
    if(missingFields.length)
      return next(new RequiredBodyError(missingFields));
    
		// If no missing fields then run router code
    return next();
  }
}

module.exports = requiredFields;

You can now go back to the router code and add this new functionality. You can add this function as a parameter to the “router.post” method just before the controller code with an array of required fields. When done correctly the code will look something like the following.

router.post("/find", requiredFields(["filename", "title"]), async (req, res, next) => {

If you request this route with no fields it should give an appropriate 400 response with a reason for the error.

Express js error handling 404.webp

The next 2 errors are very easy to handle. The first is just checking if there is an error reading the file. To do this we just check if the error parameter is not undefined and if so, return an error.

fs.readFile(`data/${filename}.json`, 'utf8', (err, data) => {
	if(err)
    return next(new Error(`Error reading file ${filename}.`));

The last error will check if the JSON can be parsed and whether the JSON is in the correct format. This can simply be done with a try-catch statement. In the catch, we will just return an error with no message since it’s just a standard 500 error and we just want to signal that something went wrong. Once all error handling is implemented the final express js route error handling code will look like the following.

// src/routes/index.js

const express = require("express");
const fs = require('fs');
const requiredFields = require("../middlewares/requiredFields");

const router = express.Router();

// Post request at /find with a requiredFileds middleware
router.post("/find", requiredFields(["filename", "title"]), async (req, res, next) => {
	// Used fields  
	const {filename, title} = req.body;
    
  fs.readFile(`data/${filename}.json`, 'utf8', (err, data) => {
		// If error when reading the file return an error
    if(err)
      return next(new Error(`Error reading file ${filename}.`));

    try {
			// Parse file
      const json = JSON.parse(data);

      const books = json.books.filter(
        val => val.title.toLowerCase().includes(title.toLowerCase()));

			// Send response
      return res.status(200).json({
        books
      })
    } catch {
			// If could not parse file then return an error
      next(new Error());
    }
  });
})

module.exports = router;

If we now send a request with a file that does not exist, we get a response that looks like the following.

Express js route error handling.webp

If you send a request with a file that is not formatted correctly you will get a response that looks like the following.

A Guide to Error Handling in Express.js.webp

Conclusion

In this article, we explored the different approaches to error handling using middleware, custom errors, and async functions. We not only saw where the server can crash but also why it crashes if not handled correctly in async functions. Finally, we looked at how 404 errors can be handled and how we can cohesively implement it with the middleware and custom errors.

With this information, you can now create scalable projects that follow best practices when it comes to express error handling. Also, you are equipped with the skills to implement the ideas since we went through a guided example using all the concepts together.

How to create custom Express.js error pages#

Express does a good job of handling 404 and 500 errors by default. However, many a times, the error is page is now what we would like it to look like. Is there a way to customize it? Yes there is.

Online, you will come across many ways of implementing custom error pages for Express, but a lot of them do not use the correct approach, and those who do, do not explain properly how to do it, or what is going on. In this post I will show you how to create custom 404 and 500 error pages the right way, and explain how and why it works.

If you are asking this question, I will assume that you already have a working Express application and you are familiar with the application code, at least somewhat. I will also assume that you created the skeleton of your app using the express command (if you did not, start using it — type express -h at the command line).

To get some context, open app.js and find these lines:

...
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
...

In the first line, we have added the router middleware, which makes defining routes in Express possible.

In the second line, we are adding Stylus to pre-process our CSS files.

In the third line, we are setting up our static directory for serving CSS, JavaScript, images etc.

You may come across some suggestions like the following to handle 404 errors:

app.get('*', function(req, res) ...

This approach is wrong, it is using a route to handle 404 error. Because the router middleware is added before the static middleware, it will intercept the requests for static file like CSS, JavaScript etc. You could make it work somehow, but it would a dirty hack job, we need to use the right approach, so abandon this method.

So what’s the right method?

We need to create two middleware to handle 404 and 500 errors. Add these two right below app.use(express.static(path.join(__dirname, 'public')));:

// Handle 404
app.use(function(req, res) {
  res.send('404: Page not Found', 404);
});

// Handle 500
app.use(function(error, req, res, next) {
  res.send('500: Internal Server Error', 500);
});

Try loading a non-existent page on your website now or generate an error by calling an undefined function in one of your route handlers. You will see your custom error pages now.

Hey, but aren’t we looking to create cool looking custom error pages?

Ah yes! Go ahead create these two files in the views directory.

404.jade

extends layout
block content
  h1= title
  p Dude, where is my page?
  a(href='/') Take me to the homepage!

500.jade

extends layout
block content
  h1= title
  p #{title}
  p #{error}

Now, update the error handling middleware.

// Handle 404
app.use(function(req, res) {
 res.status(400);
res.render('404.jade', {title: '404: File Not Found'});
});

// Handle 500
app.use(function(error, req, res, next) {
  res.status(500);
res.render('500.jade', {title:'500: Internal Server Error', error: error});
});

An important point to note is that, these two middleware must go at the very end of the Express middleware stack, else you will get unexpected results. Also, the 500 error handling middleware has an arity of 4, if you define it with anything lesser, it will fall back on the default Express 500 error handler.

Now restart you app, load the error-prone pages, and get ready to admire your witty looking, customized 404 and 500 error pages.

References#

  1. Express.js: Writing middleware

Error handling in Express.js refers to the process of capturing and responding to errors that occur during the execution of an Express application. In Express, you can handle errors using middleware functions, which are functions that have access to the request and response objects, as well as the next middleware function in the application’s request-response cycle.

Express has built-in error handling middleware, such as the app.use(function(err, req, res, next) {}) function, which can be used to handle errors that are thrown or passed to the next() function. You can also create your own error-handling middleware functions to handle specific errors in your application.

It’s important to note that in Express, the order of middleware functions is important. Error-handling middleware should be placed at the end of the middleware stack, after all, other middleware functions, so that it can catch any errors that are not handled by the other middleware.

In addition, it’s important to handle errors properly and provide a proper error message to the user, rather than returning stack traces to the client in production.

Reason for using error handling used in express.js:

  • To prevent application crashes: Without error handling, unhandled errors can cause an application to crash, leading to poor user experience and potential data loss. Error handling allows you to capture and respond to errors, preventing them from causing a crash and keeping the application running smoothly.
  • To provide meaningful error messages: Error handling allows you to provide meaningful and user-friendly error messages to your users, rather than leaving them with a blank screen or a default error message. This can help to improve the overall user experience and prevent confusion or frustration.
  • To improve debugging: Error handling allows you to capture and log errors, making it easier to debug your application and identify the root cause of any issues. This can save time and effort when troubleshooting problems with your application.
  • To comply with standards and regulations: Proper error handling is often a requirement for compliance with security standards and regulations. By handling errors correctly, you can ensure that your application meets these standards and regulations.

Ways to Perform Error Handling:

1. Middleware function: Express.js has built-in support for error-handling middleware, which allows you to handle errors that occur during the execution of the application.

Syntax:

app.use(function(error, request, response, next) {
       // Handle the error
       response.status(500).send('Internal Server Error');
});

2. Try-Catch statements: you can use try-catch statements to handle errors that occur within specific blocks of code. This ensures that any errors that occur are caught and handled in a controlled manner.

Syntax:

app.get('/', function (req, res) {
    try {
        // Code that might throw an error
    } catch (error) {
        // Handle the error
        res.status(500).send('Internal Server Error');
    }
});

3. Error logging: You can set up error logging so that any errors that occur during the execution of the application are logged to a file or a database for later analysis.

Syntax:

app.get('/', function (req, res) {
    try {
       throw new Error('Something went wrong');
    } catch (error) {
      console.error(error);
    }
});

Error codes: You can set up error codes for different types of errors that occur during the execution of the application. This makes it easier to identify and handle specific errors.

  • Error codes in Node.js are symbolic values that represent specific types of errors that can occur during the execution of a program. Error codes are usually represented as strings and are used to help identify and categorize different types of errors.
  • For example, the Node.js fs module uses error codes such as ‘ENOENT’ (no such file or directory) or ‘EACCES’ (permission denied) to represent specific types of file system errors.
  • When an error occurs in your Node.js application, you can access the error code by checking the code property of the error object. For example, if you are using the fs.readFile function, you can check the code property of the error object that is passed to the callback to determine the type of error that has occurred.

Example:

const fs = require('fs');

fs.readFile('nonexistent-file.txt', (error, data) => {
    if (error) {
        console.error(error.code);
    } else {
        console.log(data.toString());
    }
});

4. HTTP status codes: You can use HTTP status codes to indicate the type of error that occurred. For example, a status code of 400 (Bad Request) can indicate a validation error, while a status code of 500 (Internal Server Error) can indicate a server-side error.

Syntax:

 const http = require('http');

const server = http.createServer((request, response) => {
  response.statusCode = 200;
  response.end('OK');
});

server.listen(8080);
  • By using any of the above, you can handle errors in a controlled and efficient manner, and ensure that your application is robust and stable.

Let’s see some basic examples and explanations for Error Handling in Express.js:

Example 1: Using a middleware function: You can use a middleware function to handle errors that occur during the execution of an application. The middleware function should have four arguments: error, request, response, and next.

Javascript

const express = require('express');

const app = express();

const errorHandler = (err, req, res, next) => {

    console.error(err.stack);

    res.status(500).send('Something went wrong!');

};

app.use((req, res, next) => {

    throw new Error('Something broke!');

});

app.use(errorHandler);

app.listen(3000, () => {

    console.log('App is listening on port 3000');

});

Steps to run the application: Write the below code in the terminal to run the application:

node index.js

Output: 

Explanation: 

  • In this example, we define a custom error-handling middleware function errorhandler that logs the error stack and sends a response with a status code of 500 and the message “Something went wrong!”.
  • We then use the custom error handling middleware by adding the app.use(errorhandler) after defining it.
  • This error-handling middleware will catch any errors thrown in the previous middleware or routes, and handle them according to the logic defined in the errorHandler function.
  • The first line App is listening on port 3000 is logged when the Express app starts listening on port 3000.
  • If you make a request to the app, the custom middleware will throw an error, which will then be caught by the error-handling middleware. The error stack trace will be logged to the console, and the response sent to the client will have a status code of 500 and the message “Something went wrong!”.

Example 2: Using the try-catch statement: You can use the try-catch statement to handle errors that occur within a specific block of code.

Javascript

const express = require('express');

const app = express();

app.get('/', (req, res, next) => {

    try {

        const data = someFunctionThatMightThrowError();

        res.status(200).json(

            { message: 'Data retrieved successfully', data });

    } catch (error) {

        next(error);

    }

});

app.use((err, req, res, next) => {

    console.error(err.stack);

    res.status(500).json(

        { message: 'Something went wrong!' });

});

app.listen(3000, () => {

    console.log('App is listening on port 3000');

});

Explanation:

  • In this example, we wrap the code that might throw an error in a try block. If an error is thrown, it will be caught by the corresponding catch block, which logs the error stack and sends a response with a status code of 500 and the message “Something went wrong!”.
  • This approach allows for more fine-grained error handling, as the try-catch statement can be used multiple times in different middleware functions or routes.

Steps to run the application: Write the below code in the terminal to run the application:

node index.js

Output:

Explanation:

  • If you make a request to the app, the custom middleware will throw an error, which will then be caught by the try-catch statement. The error stack trace will be logged to the console, and the response sent to the client will have a status code of 500 and the message “Something went wrong!”.
  • Note that the [ERROR STACK TRACE] part of the output will vary depending on the exact error that was thrown. It will contain details about the error, such as the error message and the location in the code where the error was thrown.
  • his output will be displayed if you make a request to the app and an error is thrown by the custom middleware. The error stack trace will be logged to the console and the response sent to the client will have a status code of 500 and the message “Something went wrong!”.
  • This output will be displayed when the Express app starts listening on port 3000. No error will be thrown if you do not make any requests to the app.

Example 3: Using the next() function: You can use the next() function to pass errors to the next middleware function in the chain.

Javascript

const express = require('express');

const app = express();

app.get('/', (req, res, next) => {

    const data = someFunctionThatMightThrowError();

    if (!data) {

        return next(new Error('Error retrieving data'));

    }

    res.status(200).json(

        { message: 'Data retrieved successfully', data });

});

app.use((err, req, res, next) => {

    console.error(err.stack);

    res.status(500).json(

        { message: 'Something went wrong!' });

});

app.listen(3000, () => {

    console.log('App is listening on port 3000');

});

Explanation: 

  • In this example, we have two middleware functions. The first middleware function throws an error, and the second middleware function is used for error handling. If an error is thrown in the first middleware function, the control flow is passed to the second middleware function using the next() function. The error is then logged to the console and a response with a status code of 500 and the message “Something went wrong!” is sent to the client.
  • This approach allows for error handling to be handled separately from the middleware functions that perform the core functionality of the application.

Steps to run the application: Write the below code in the terminal to run the application:

node index.js

Here’s an example using curl:

  • Open a terminal or command prompt.
  • Navigate to the directory where the program is located.
  • Start the application by running node app.js.
  • In another terminal window, run the following command to make a request to the ‘/’ endpoint:
curl http://localhost:3000

Output:

  • If you make a request to the app, the first middleware function will throw an error. The error will be passed to the second middleware function using the next() function, where it will be logged to the console and a response with a status code of 500 and the message “Something went wrong!” will be sent to the client.
  • Note that the [ERROR STACK TRACE] part of the output will vary depending on the exact error that was thrown. It will contain details about the error, such as the error message and the location in the code where the error was thrown.

Advantages of error handling used in express.js:

  1. Improved user experience: Error handling allows you to provide meaningful and user-friendly error messages to your users, rather than leaving them with a blank screen or a default error message. This improves the overall user experience and can help to prevent confusion or frustration.
  2. Better debugging: When errors occur in an application, it can be difficult to identify the cause without proper error handling. By capturing and logging errors, you can more easily debug your application and identify the root cause of any issues.
  3. Increased application stability: Error handling helps to prevent unhandled errors from crashing your application, which can lead to increased stability and fewer downtime incidents.
  4. Better maintainability: Error handling makes it easier to maintain your application by providing a clear and consistent way to handle errors. This can make it easier to identify and fix bugs, as well as to add new features.

Disadvantages of error handling used in express.js:

  1. Increased complexity: Error handling can add complexity to your application, as it requires you to anticipate and plan for potential errors. This can make your code more difficult to understand and maintain.
  2. Overhead: Error handling can add overhead to your application, as it requires additional logic and processing to capture and respond to errors. This can impact the performance of your application.
  3. False alarms: If error handling is not implemented correctly, it can lead to false alarms or unnecessary error messages being displayed to users. This can create confusion and damage user trust.
  4. Security risks: Improper error handling can create security risks, as it can reveal sensitive information or provide attackers with clues about potential vulnerabilities in your application.

Last Updated :
16 Feb, 2023

Like Article

Save Article

7 месяцев назад·4 мин. на чтение

Из-за неопределенного характера JavaScript существует множество способов выполнения одной задачи. Это может стать как достоинством, так и недостатком, особенно при работе в более крупной команде. Именно здесь в игру вступают процессы и руководящие принципы.

Предусловия

  • Установленный NodeJS
  • Знание NodeJS и Express.js
  • Знание того, как работает middleware в Express.js

Настройка проекта

Создадим базовое приложение Express.js с одним эндпоинтом. Этот эндпоинт (или ручка) будет методом POST, который принимает два входных параметра title и author.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(bodyParser.json());

app.post('/post', async (req, res) => {
  const { title, author } = req.body;

  if (!title || !author) {
    return res.status(400).json({
      status: 'error',
      message: 'Missing required fields: title or author'
    });
  }

  try {
    const post = await db.post.insert({ title, author });
    res.json(post);
  } catch (error) {
    return res.status(500).json({
      status: 'error',
      message: 'Internal Server Error'
    });
  }
});

app.listen(port, () =>
  console.log(`app is listening at http://localhost:${port}`)
);

Мы проверяем, существуют ли title и author, если нет, мы выбрасываем ошибку 400 и отправляем обратно JSON со статусом и сообщением.
Если title и author существуют, приложение все равно будет аварийно завершать работу, потому что db не определена, и наш блок try/catch поймает его и отправит обратно ошибку 500 и JSON со статусом и сообщением.
Со временем, по мере роста количества эндпоинтов и проверок, ввод res.status(4xx).json({ some: JSON }) каждый раз может быстро стать громоздким, а также создать большую избыточность кода. Почему бы не сделать что-то вроде throw new BadRequest('message')? Давайте посмотрим, как мы можем это реализовать.

Создание утилит для ошибок

Теперь создадим функции, которую мы можем использовать для генерации ошибок. Создадим новую папку /utils и файл errors.js.

// /utils/errors.js

class GeneralError extends Error {
  constructor(message) {
    super();
    this.message = message;
  }

  getCode() {
    if (this instanceof BadRequest) {
      return 400;
    } if (this instanceof NotFound) {
      return 404;
    }
    return 500;
  }
}

class BadRequest extends GeneralError { }
class NotFound extends GeneralError { }

module.exports = {
  GeneralError,
  BadRequest,
  NotFound
};

Этот файл определяет, какие ошибки мы можем выбросить в нашем приложении. Класс GeneralError расширяет Error и используется для получения наших сообщений и кодов состояния.
Здесь у нас есть BadRequest и NotFound, которые расширяют GeneralError. Мы также указываем их коды ошибок в блоке getCode в GeneralError.
Для простоты этой демонстрации у нас будут толькоBadRequest и NotFound. Если вы хотите добавить другие типы ошибок, все, что вам нужно сделать, это создать новый класс, который расширяет GeneralError и обновить его код состояния внутри блока getCode.

Создание middleware для обработки ошибок

Теперь мы сосредоточимся на реализации express middleware для обработки ошибок в нашем приложении. Создадим новый файл /middleware/handleErrors.js.

// /middleware/handleErrors.js

const { GeneralError } = require('../utils/errors');

const handleErrors = (err, req, res, next) => {
  if (err instanceof GeneralError) {
    return res.status(err.getCode()).json({
      status: 'error',
      message: err.message
    });
  }

  return res.status(500).json({
    status: 'error',
    message: err.message
  });
}


module.exports = handleErrors;

Примечание: middleware для обработки ошибок принимает 4 аргумента (ошибка в качестве первого аргумента), а не 3 аргумента для обычного middleware .
Функция middleware handleErrors проверяет, является ли переданная ошибка экземпляром GeneralError. Если это так, мы возвращаем код состояния и тело JSON со статусом и сообщением.

Использование middleware для обработки ошибок

Давайте обновим наше приложение и эндпоинт, чтобы использовать наш недавно созданный middleware для обработки ошибок.
Middleware для обработки ошибок должно быть помещено последним, после всех других middleware и маршрутов, чтобы оно функционировало должным образом.

const express = require('express');
const bodyParser = require('body-parser');
const handleErrors = require('./middleware/handleErrors');
const { BadRequest } = require('./utils/errors');

const app = express();
const port = 3000;

app.use(bodyParser.json());

app.post('/post', async (req, res, next) => {
  const { title, author } = req.body;
  
  try {
    if (!title || !author) {
      throw new BadRequest('Missing required fields: title or author');  // строка 16
    }
    const post = await db.post.insert({ title, author });
    res.json(post);
  } catch (err) {
    next(err)
  }
});

app.use(handleErrors); // строка 25

app.listen(port, () =>
  console.log(`app is listening at http://localhost:${port}`)
);

Во-первых, мы импортируем handleErrors и регистрируем его как middleware, как показано в строке 25.
Мы также импортируем BadReqest и обновляем строку 16, чтобы выбросить новый BadRequest, если title и author отсутствуют.
Наконец, мы добавляем next в качестве третьего аргумента в наш обработчик маршрута. Затем мы обновляем блок catch, чтобы передать ошибки в next чтобы наш обработчик ошибок мог обработать его.

Тестирование middleware для обработки ошибок

Для тестирования middleware используем Postman.
Сначала мы делаем POST-запрос без body. Мы получаем ошибку 400 со статусом и сообщением в формате JSON.

{
  "status": "error",
  "message": "Missing required fields: title or author"
}

Теперь давайте сделаем еще один запрос POST и передадим title и author. На этот раз мы получаем ошибку 500 со статусом и сообщением в JSON.

{
  "status": "error",
  "message": "db is not defined"
}

Простое и чистое решение для обработки ошибок в приложении Express.js.

Итоги

В этой статье мы рассмотрели, как создать middleware для обработки ошибок для приложения Express.js. Это позволит поддерживать чистоту кода с меньшим количеством избыточного кода. Все, что нам нужно сделать, это выбросить ошибку и передать сообщение. Эта реализация добавляет гибкость для добавления дополнительных классов ошибок для вашего приложения по мере необходимости.

5 месяцев назад·6 мин. на чтение

Простые проекты

1. Приложение «Список дел» (Todo list)

Приложение «Список дел» — это простой, но важный проект для любого разработчика. Это позволяет вам создать список задач и упорядочить их на основе их приоритета и сроков выполнения. Данный проект может быть реализован с использованием различных технологий и фреймворков, что делает его отличной возможностью как для начинающих, так и для продвинутых разработчиков попрактиковаться в своих навыках.
Вот несколько идей для функций, которые можно добавить в приложение со списком дел:

  • Теги и категории: Разрешить пользователям классифицировать задачи на основе тегов или категорий (например, работа, личные, поручения), чтобы помочь им организовать свой список дел.
  • Автоматическое сохранение: автоматическое сохранение элементов списка дел в локальном хранилище каждый раз, когда вносятся изменения, чтобы пользователю не приходилось беспокоиться о сохранении списка вручную.
  • Поиск: добавьте в приложение панель поиска, которая может искать элементы в списке дел и сохранять историю поиска пользователя в локальном хранилище.

2. Веб-сайт личного портфолио

Веб-сайт для личного портфолио — это цифровое пространство, где люди могут продемонстрировать свои навыки, опыт и достижения потенциальным работодателям, клиентам или сотрудникам. Он служит онлайн-резюме или портфолио, позволяя посетителям узнать больше о прошлом, опыте и предыдущих проектах человека.
Хорошо продуманный веб-сайт личного портфолио может помочь людям выделиться на конкурентном рынке труда, привлечь новых клиентов и создать свой личный бренд. Веб-сайт может включать в себя различные разделы, такие как страница «Обо мне», страница портфолио с образцами предыдущих работ, список навыков и опыта, контактная информация, а также отзывы или рекомендации от предыдущих клиентов или работодателей.
Веб-сайты личного портфолио можно настроить так, чтобы они отражали стиль и индивидуальность человека, используя цвета, шрифты, изображения и другие элементы дизайна. Они также могут включать интерактивные функции, такие как анимация, видео или слайдеры, чтобы сделать веб-сайт более привлекательным и динамичным.

3. Генератор случайных цитат

Генератор случайных цитат — это простое веб-приложение, которое генерирует случайные цитаты или высказывания при нажатии кнопки. Этот проект может стать отличным способом попрактиковаться в навыках веб-разработки, включая получение данных из API, отображение динамического контента и стилизацию с помощью CSS. Пользовательский интерфейс может включать в себя простой дизайн с кнопкой и пространством для отображения предложения.

4. Простой калькулятор

Простой калькулятор — это проект, который может стать отличным способом для разработчиков попрактиковаться в своих навыках в JavaScript и HTML/CSS. Проект включает в себя создание калькулятора, который может выполнять основные математические операции, такие как сложение, вычитание, умножение и деление.
Калькулятор должен иметь простой пользовательский интерфейс с кнопками для каждого из чисел, операторами и понятной функцией. Калькулятор также должен обрабатывать ввод как с клавиатуры, так и с мыши.
Чтобы немного усложнить проект, разработчики также могут включить дополнительные функции, такие как функция десятичной запятой, процентные вычисления и функции памяти. Калькулятор также можно стилизовать, чтобы сделать его визуально привлекательным и отзывчивым на разных устройствах.

5. Приложение «Погода»

Погодное приложение — это приложение, которое позволяет пользователям просматривать прогноз погоды для своего местоположения или любого другого места, которое они выберут. Приложение обычно отображает такую информацию, как температура, влажность, скорость ветра и осадки.

Проекты средней сложности

1. Веб-сайт электронной коммерции (E-commerce)

Веб-сайт электронной коммерции — это цифровая платформа, которая позволяет предприятиям продавать свои товары или услуги в Интернете. Покупатели могут просматривать товары, добавлять их в корзину и совершать покупки с помощью различных способов оплаты. Веб-сайт также включает в себя такие функции, как поиск, сортировка и фильтрация, чтобы облегчить покупателям процесс покупок.

2. Социальная сеть

Платформа социальных сетей — это веб-приложение, которое позволяет пользователям создавать контент и делиться им, общаться с другими людьми и создавать сеть контактов. Обычно пользователи могут создавать профиль, публиковать обновления, фотографии или видео, подписываться на других пользователей и взаимодействовать с их контентом с помощью лайков, комментариев и репостов. Некоторые социальные сети также предлагают дополнительные функции, такие как обмен сообщениями, прямые трансляции и управление событиями.

3. Онлайн чат

Приложение для онлайн-чата — это платформа, которая позволяет пользователям общаться друг с другом в режиме реального времени с помощью текста, аудио или видео. Приложение обычно включает в себя такие функции, как аутентификация пользователей, чаты, личные сообщения и обмен файлами. Пользователи могут присоединяться к чатам или создавать свои собственные и участвовать в обсуждениях с другими пользователями, имеющими схожие интересы. Некоторые приложения для онлайн-чата также позволяют пользователям совершать голосовые или видеозвонки внутри платформы.

4. Отслеживание расходов

Это приложение для управления финансами, которое позволяет пользователям отслеживать свои расходы и управлять своим бюджетом. Некоторые функции, которые можно добавить в трекер расходов:

  • Категоризация: категоризация расходов, чтобы дать пользователям представление о том, куда они тратят свои деньги.
  • Бюджетирования: Возможность установить бюджет для разных категорий и отслеживать расходы по нему.
  • Визуализация данных: Предоставьте пользователям графики и диаграммы, которые визуализируют их расходы по категориям или периодам времени, давая им четкое представление об их привычках и моделях расходов.

5. Рецепты

Приложение рецептов — это приложение, которое предоставляет пользователям коллекцию рецептов различных блюд. Пользователи могут просматривать рецепты и находить вдохновение для своего следующего приема пищи. Приложение обычно включает в себя такие функции, как поиск, фильтрация и сохранение любимых рецептов.
Дополнительные функции, которые следует добавить в приложение рецептов, включают:

  • Список покупок: Пользователи могут добавлять ингредиенты в список покупок прямо из рецепта, что упрощает приготовление блюда.
  • Информация о питании: Отображение информации о питании, такой как калории, жиры и белки для каждого рецепта, может помочь пользователям принимать обоснованные решения о своем рационе.
  • Обмен в социальных сетях: Предоставление пользователям возможности делиться своими любимыми рецептами в социальных сетях может помочь приложению завоевать популярность и расширить свою пользовательскую базу.

Трудные проекты

1. Чат-бот с искусственным интеллектом

Чат-бот с искусственным интеллектом — это компьютерная программа, которая использует искусственный интеллект для имитации человеческого разговора. Эти чат-боты предназначены для того, чтобы реагировать на ввод пользователя и предоставлять соответствующую информацию или помощь. Они обычно используются для обслуживания клиентов, личных помощников и других подобных приложений.

2. Веб-сайт потокового видео

Веб-сайт потокового видео — это платформа, которая позволяет пользователям смотреть и обмениваться видео в Интернете. Эти веб-сайты обычно предлагают различные видео, от коротких клипов до полнометражных фильмов и телешоу. Некоторые из ключевых функций, которые могут быть включены в веб-сайт потокового видео:

  • Категоризация контента: категоризация видео на основе их жанра, языка, продолжительности и других параметров, чтобы помочь пользователям легко найти контент, который они ищут.
  • Профили пользователей и плейлисты: позволяют пользователям создавать свои собственные профили и плейлисты, сохранять видео для последующего просмотра и делиться своими любимыми видео с другими.
  • Управление качеством видео и воспроизведением: Обеспечение высококачественной потоковой передачи видео с настраиваемыми элементами управления воспроизведением, такими как воспроизведение, пауза, перемотка назад и вперед.

3. Веб-сайт доски объявлений

Веб-сайт доски объявлений о вакансиях — это платформа, которая позволяет компаниям размещать списки вакансий, а соискателям — искать и подавать заявки на работу. Некоторые ключевые функции, которые могут быть включены в веб-сайт доски объявлений:

  • Фильтры расширенного поиска: позволяют соискателям фильтровать свой поиск по различным критериям, таким как тип работы, местоположение, уровень опыта и диапазон заработной платы.
  • Оповещения о вакансиях: разрешите пользователям подписываться на электронную почту или push-уведомления о публикации новых вакансий, соответствующих их критериям.
  • Конструктор резюме: инструмент, который позволяет соискателям создавать профессиональное резюме для подачи вместе с заявлением о приеме на работу.

4. Онлайн-редактор кода

Онлайн-редактор кода — это веб-приложение, которое позволяет разработчикам писать, редактировать и тестировать свой код прямо в браузере. Он предоставляет пользователям платформу для экспериментов с различными языками программирования и фреймворками, а также позволяет сотрудничать с другими разработчиками в режиме реального времени.
Добавляемые функции:

  • Подсветка синтаксиса: редактор должен выделить синтаксис кода, чтобы его было легче читать и понимать.
  • Автозаполнение: Редактор должен предлагать фрагменты кода и автозаполнение кода, чтобы сэкономить время и свести к минимуму ошибки.
  • Поддержка нескольких языков: редактор должен поддерживать несколько языков программирования, чтобы сделать его универсальным и полезным для более широкого круга разработчиков.

5. Платформа для ведения блогов

Платформа для ведения блогов — это веб-сайт, который позволяет отдельным лицам или организациям создавать, публиковать и управлять собственным контентом блога. Подобно Medium, он позволяет писателям публиковать сообщения на различные темы и предлагает такие функции, как интеграция с социальными сетями, комментирование и аналитика, чтобы помочь блоггерам расширить свою аудиторию. Вот некоторые важные функции, которые следует рассмотреть при добавлении на платформу для ведения блогов:

  • Учетные записи пользователей: возможность для пользователей создавать учетные записи для публикации и управления собственным контентом блога.
  • Система комментирования: система комментирования, позволяющая пользователям взаимодействовать с контентом и участвовать в обсуждении.
  • Настройка: параметры настройки, такие как темы, шрифты и цвета, позволяющие пользователям персонализировать внешний вид своего блога.

Еще идеи

Смотреть на Rutube

Answer by Sofia Willis

Please stand by, while we are checking your browser…,If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices.,Completing the CAPTCHA proves you are a human and gives you temporary access to the web property.

More Details Refer


Answer by Cora French

You need to export your getTeamData function from dotnetFin.js file. So just change,,

3

In dotnetFin.js, do you export the function via module.exports.getTeamData = getTeamData ?

– Himmet Avsar
Oct 20 ’15 at 11:00

,Connect and share knowledge within a single location that is structured and easy to search.

You need to export your getTeamData function from dotnetFin.js file. So just change,

var getTeamData = function () {
    return dotnetTeam;
};

with

exports.getTeamData = function () {
    return dotnetTeam;
};

Answer by Maxwell Woodward

In your case, when you miss out the semicolon after the array assignment, the array literal on the following line is being interpreted as a reference to an element within the array, which is of course undefined. You can read your code as:

router.post('/addRows', function (req, res) {
    const saveData = [][1,2,3,4,5,6,7,8,9,10].map((i) => {
        console.log(i)
        saveData.push(i)
        if (saveData.length === 10) {
            res.status(200).json({'data': saveData});
        }
    })
})

That may not look valid but it is — the second array literal is being parsed as a property lookup containing an expression with comma («grouping») operators. The comma operator returns its final operand, so you can simplify the above:

router.post('/addRows', function (req, res) {
    const saveData = [][10].map((i) => {
        console.log(i)
        saveData.push(i)
        if (saveData.length === 10) {
            res.status(200).json({'data': saveData});
        }
    })
})

Answer by Mary Carrillo

More Details Refer


Answer by Grady Moreno

Check if the error is thrown from your custom code and fix the issue, if possible.,Proceed to Execution Error in an Edge Policy if
it is a policy error.,If it’s a Node.js backend server:

Check if the error is thrown from your custom code and fix the issue, if possible.

If the error is not thrown from your custom code or if you need assistance, contact
Apigee Support.

You may get the following error message:

HTTP/1.1 500 Internal Server Error

In some cases, you may observe another error message which has more details. Here is a sample
error message:

{  
   "fault":{  
      "detail":{  
         "errorcode":"steps.servicecallout.ExecutionFailed"
      },
      "faultstring":"Execution of ServiceCallout callWCSAuthServiceCallout failed. Reason: ResponseCode 400 is treated as error"
   }
}
{ 
"fault":
     { "detail":
           { "errorcode":"steps.servicecallout.ExecutionFailed"
           },"faultstring":"Execution of ServiceCallout service_callout_v3_store_by_lat_lon
 failed. Reason: ResponseCode 404 is treated as error"
          }
     } 
}

<ServiceCallout async="false" continueOnError="true" enabled="true" name="Callout.OamCookieValidation"> 
  <DisplayName>Callout.OamCookieValidation</DisplayName>    
  <Properties />    
  <Request clearPayload="true" variable="serviceCallout.oamCookieValidationRequest">       
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>    
  </Request>    
  <Response>serviceCallout.oamCookieValidationResponse</Response>    
  <HTTPTargetConnection>       
    <Properties />       
    <URL>http://{Url}</URL>    
  </HTTPTargetConnection> 
</ServiceCallout>

/opt/apigee/var/log/edge-message-processor/system.log

2017-05-05 07:48:18,653 org:myorg env:prod api:myapi rev:834 messageid:rrt-04984fed9e5ad3551-c-wo-32168-77563  NIOThread@5 ERROR HTTP.CLIENT - HTTPClient$Context.onTimeout() : ClientChannel[C:]@149081 useCount=1 bytesRead=0 bytesWritten=0 age=3002ms lastIO=3002ms .onConnectTimeout connectAddress=mybackend.domain.com/XX.XX.XX.XX:443 resolvedAddress=mybackend.domain.com/XX.XX.XX.XX

telnet

telnet mybackend.domain.com 443 
Trying XX.XX.XX.XX... 
telnet: connect to address XX.XX.XX.XX: Connection timed out

Answer by Sutton Noble

More Details Refer


Answer by Kinslee Jacobson

Modules from Node.js. Up to date modules will trigger an admin console error of 500 if you have a Node.js-based site.,Internal Server Error 500 may be triggered for a variety of different reasons. The most popular ones are here:,This article describes what an error of 500 means, how you get an HTTP 500 code, as well as how to fix such errors.

More Details Refer


Answer by Remi Chapman

Reload a web page. You can do that by clicking the refresh/reload button, pressing F5 or Ctrl + R, or trying the URL again from the address bar. ,What is HTTP Status 500 Internal Server Error and How To Fix It,Finally, What is HTTP Status 500 Internal Server Error and How To Fix It tutorial is over.

More Details Refer


Answer by Conor Warren

Depending on if you have admin rights to a debug conference for the flawed Interface or if the back-end is a Node.js server, repeat the process given below.,Verify that the backend server was responsible for the mistake. See and identify the cause of the issue for information.,Contact the administrators of the domain. The only choice left is to get in contact with the person responsible for running the website.

More Details Refer


Answer by Fox Coffey

I have a simple react app(form ) that uses node api to verify some data on that page. I have successfully deployed app to the digital ocean .
But on browser going to my app gives 500 Internal Server Error.,Hi ,

I have successfully deployed a React app with node backend using App Platform.
But on going live App, m getting below error,

Cannot GET /

Thanks,Hi there, I have an Node/React app deployed to App Platform. I am facing a problem when I deploy any changes, I am not served the new production build files. I am served files but nothing gets rendered on the page. If I open the chrome…

More Details Refer


Answer by Hugh Crawford

I have developed a full-stack application with Vue 2, Node , Express and Postgres. I could deploy the application to Azure , and the system coming up, but when I try to do register user with Register page that I have created , I get » POST … 500 (Internal Server Error) «, as I have tried with Postman , there is no issue in saving user data with same post controller .,[MSDN Redirect] Best suitable approach to host Angular 8 application into Azure web app,Django app deployed on Azure app services not appearing

Notice that I have set BaseURL to ‘’ in Api.js ( Client ):

 import axios from ‘axios’
 import store from ‘@/store/store’
 export default () => {
    return axios.create({
       baseURL: ‘’,
       headers: {
            Authorization: Bearer ${store.state.token}
       }
    })
 }

this is Register controller in /Controller folder :

 //Registering user
 async register(req, res) {
 const hash = bcrypt.hashSync(req.body.password, 10);
      try {
          const user = await User.create(
          Object.assign(req.body, { password: hash })
       );
    const userJson = user.toJSON();
    res.send({
           user: userJson,
           token: jwtSignUser(userJson),
          });
   } catch (err) {
      res.status(500).send({
      error: There is error in registering: ${err},
  });
  }
 },

I have added the following web.config file in dist folder, but it doesn’t resolve the issue , also I have added web.config in root and has same issue :

 <configuration>
   <system.webServer>
     <staticContent>
       <mimeMap fileExtension="woff" mimeType="application/font-woff" />
       <mimeMap fileExtension="woff2" mimeType="application/font-woff" /> 
     </staticContent>
     <rewrite>
          
       <rules>
                 <clear />
                 <rule name="Redirect to https" stopProcessing="true">
                     <match url=".*" />
                     <conditions>
                         <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                     </conditions>
                     <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                 </rule>
             </rules>
     </rewrite>
         
       <httpErrors>     
           <remove statusCode="404" subStatusCode="-1" />                
           <remove statusCode="500" subStatusCode="-1" />
           <error statusCode="404" path="/survey/notfound" responseMode="ExecuteURL" />                
           <error statusCode="500" path="/survey/error" responseMode="ExecuteURL" />
       </httpErrors>
       <modules runAllManagedModulesForAllRequests="true"/>
   </system.webServer>
 </configuration>

Понравилась статья? Поделить с друзьями:
  • Expected array ошибка vba excel
  • Explorer ошибка 1001
  • Explay c360 ошибка файла
  • Explorer exe ошибка файловой системы 2147416359
  • Expected identifier vba ошибка