Experience gained from node. JS Errors

Source: Internet
Author: User
Tags stack trace

How many times have you found yourself viewing stack traces in a terminal or monitoring system, but you can't see why? If your answer is "many times", then you should look at this post. It doesn't matter if you don't run into this kind of situation often, you can also read this article for boredom.

When dealing with complex data from a node. JS server, it is important to learn from the errors that can be returned to the requester. When a request is processed, an error occurs that causes another error in the link to occur, and the problem arises. When this script appears, once you generate a new error and return it to the link, you lose all connections to the original error.
Darwin
Darwin
Translated 5 days ago

0 Person Top

Top
The translation is good Oh!

At Codefresh, we spent a lot of time trying to find the best pattern to deal with these situations. What we really want is to be able to make a mistake that can link to the previous error and have the ability to get aggregated information for the entire chain. The interface we want to interface with will be very simple and more conducive to expansion and improvement.

We explore existing modules to support our needs. We found that the only module that satisfies the requirements is werror.

' Werror ' provides you with the ability to package existing errors and new errors. The interface is very cool and simple, so we decided to give it a try. After a period of intensive use, we have come up with some things that are not well done:

The error of the stack trace does not exceed the entire chain, but only the high error of the stack trace is generated.

It has no ability to simply create your own type of error.

Extending the additional behavior of the error, you need to extend their code.

No if
No if
Translated 5 days ago

0 Person Top

Top
The translation is good Oh!
Introduction Cferror

Based on our extensive experience, we will respond to all requests with an error handling module. All relevant information and documentation can be found here: http://codefresh-io.github.io/cf-errors.

Use a real Express example to see how cferror is used. Create an Express application (Tengyun technology ty300.com) that handles a single request through a specific route. This request requires a user's information to be queried from the Mongo database. Now define a route and a function that is responsible for getting user information from the DB.

var cferror = require (' cf-errors ');
var Errors = cferror.errors;
var Q = require (' q ');
var express = require (' Express ');

var usernotfounderror = {
Name: "Usernotfounderror"
};

var app = Express ();

App.get ('/user/:id ', function (request, response, next) {
var userId = request.params.id;
if (userId!== "Coolid") {
Return Next (New Cferror (Errors.Http.BadRequest, {
Message: "Id must be coolid.",
INTERNALCODE:04001,
Recognized:true
}));
}

Finduserbyid (USERID)
. Done (user) => {
Response.send (user);
}, (Err) => {
if (err.name = = = Usernotfounderror.name) {
Next (New Cferror (Errors.Http.NotFound, {
internalcode:04041,
Cause:err,
Message: ' User ${userid} could not being found ',
Recognized:true
}));
}
else {
Next (New Cferror (Errors.Http.InternalServer, {
INTERNALCODE:05001,
Cause:err
}));
}
});
});

var Finduserbyid = function (userId) {
Return User.findone ({_id:userid})
. exec (user) => {
if (user) {
return user;
}
else {
Return Q.reject (New Cferror (Usernotfounderror, ' Failed to retrieve User: ${userid} '));
}
})
};

There are a few things to note:

When you create an error message, you can extend it from a pre-defined HTTP error.

When creating an error message, you can add a ' cause ' attribute to connect to the previous error and form the error chain (Getting Started tutorial qkxue.net). In this way, when printing errors associated with the call stack, you can get the complete error chain of the call stack information, so that it is easy to identify when reading.

You can add various fields to the error message object. Later I will explain the use of ' internalcode ' and ' recognized '.

You can define the error object outside of your code, and then reference it when you create the error message.

Border
Border
Translated 5 days ago

0 Person Top

Top
The translation is good Oh!

Next, add an error-handling middleware to the Express app.
App.use (function (Err, request, response, next) {
var error;
if (! ( Err instanceof Cferror)) {
Error = new Cferror (Errors.Http.InternalServer, {
Cause:err
});
}
else {
if (!err.statuscode) {
Error = new Cferror (Errors.Http.InternalServer, {
Cause:err
});
}
else {
Error = Err;
}
}

Console.error (Error.stack);
Return Response.Status (Error.statuscode). Send (Error.message);
});

Attention:

Ensure that the last occurrence of the error is output to the log, and that the ' Cferror ' object is always returned to the user. This way you can add additional logic to the error handling middleware.

All predefined HTTP errors have the ' StatusCode ' attribute and the ' message ' property, and they are all properties of the and.

Extended error messages allow you to add logic to handle errors in one place. When creating an error message, you do not have to consider printing each Error object, and then you can print the trace information of the call stack at once, which contains the full execution process and context data.

Now change the method to return an error to the client, returning an object to replace the top-level error message.

Return Response.Status (Error.statuscode). Send ({
Message:error.message,
StatusCode:error.statusCode,
InternalCode:error.internalCode
});

Very good! Now we have a procedure that returns an error to the client.
Border
Border
Translated 5 days ago

0 Person Top

Top
The translation is good Oh!

Notifying the monitor (monitoring process) of error messages

In Codefresh, we use Newrelic as the APM Monitor. Note that the error message that we generate and trigger to Newrelic is divided into two categories: the first class contains various error messages generated and thrown on our servers due to improper operation. The other is the various error messages (business exceptions) that our servers correctly parse to handle the exception parts that are generated.

Reporting a second type of error to newrelic causes Apdex points to degrade predictably, which leads to false alarms from our alarm system.

So we have a new convention that when we can generalize a generated error into the result of a system's correct behavior, we construct an Error object and attach a recognized field to it. We want to have the ability to recognized a mark on an error in the wrong chain, but still get its value, even if a higher-level error does not contain the tag. We expose a getfirstvalue function on the Cferror object to get the first value it encounters on the entire error chain. Let's use the code below to see how it's used in Codefresh.

App.use (function (Err, request, response, next) {
var error;
if (! ( Err instanceof Cferror)) {
Error = new Cferror (Errors.Http.InternalServer, {
Cause:err
});
}
else {
if (!err.statuscode) {
Error = new Cferror (Errors.Http.InternalServer, {
Cause:err
});
}
else {
Error = Err;
}
}

if (!error.getfirstvalue (' recognized ')) {
Nr.noticeerror (Error); Report to monitoring systems (Newrelic)
}

Console.error (Error.stack);
Return Response.Status (Error.statuscode). Send ({
Message:error.message,
StatusCode:error.statusCode,
InternalCode:error.internalCode
});
});
laozhang127276
laozhang127276
Translated 4 days ago

0 Person Top

Top
The translation is good Oh!

Attention:

Because we know that only the Cferror object needs to be processed, we just need to add two lines of code.

Now that you have identified the actual errors to be sent, you should manually turn off the option to send the error automatically when using New Relic. To achieve this, all HTTP error status codes need to be manually added to the ' ignore_status_codes ' field in ' Newrelic.js '. We have proposed to the New Relic support team that there is an easier way to do this.


Exports.config = {
Error_collector: {
Ignore_status_codes: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
}
};
Summary

To deal with errors well requires not only a good error-handling module, but also a process that defines how and when and where to handle errors. This requires you to follow your own design pattern, or else it will be a mess.

It is important to report actual errors to the monitoring system only, so your company can focus on checking and handling the problems that occur.

Manuscripts: Diligent Learning qkxue.net

Experience gained from node. JS Errors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.