Detailed description of custom error types in Node. js and node. js
Preface
In general, few people will consider how to deal with the wrong policies generated by the application. In the debugging process, they simply useconsole.log(‘error')
Locating errors is basically enough. By leaving this debugging information, we will be able to improve the maintainability and time for future debugging. Therefore, the error message is very important. At the same time, it will bring some bad usage. The custom error types have been used in recent projects. I think it is necessary to have a deep understanding of them, so I wrote this article to facilitate reading as needed.
Subclassing Error
First, we can define an Error subclass. PassObject.create
Andutil.inherits
It is easy to achieve:
var assert = require('assert');var util = require('util');function NotFound(msg){ Error.call(this); this.message = msg;}util.inherits(NotFound, Error);var error = new NotFound('not found');assert(error.message);assert(error instanceof NotFound);assert(error instanceof Error);assert.equal(error instanceof RangeError, false);
You can useinstanceof
To check the error type and handle it according to the type.
The above Code sets the built-inmessage
Anderror
YesNotFound
AndError
But notRangeError
.
Ifexpress
Framework, you can set otherproperties
Leterror
Become more useful.
For example, when processing an HTTP Error, you can write it as follows:
function NotFound(msg) { Error.call(this); this.message = msg; this.statusCode = 404;}
Now, you can use the error processing middleware to process error information:
app.use(function(err, req, res, next) { console.error(err.stack); if (!err.statusCode || err.statusCode === 500) { emails.error({ err: err, req: req }); } res.send(err.statusCode || 500, err.message);});
This will send the HTTP status code to the browser, whenerr
OfstatusCode
If the value is not set or equal to 500, this error is sent by email. In this way, the 404,401,403 errors and so on can be ruled out.
Readconsole.error(err.stack)
In fact, it does not work as expected. node and chrome can be used based on V8.Error.captureStackTrace(this, arguments.callee)
To trace the stack.
var NotFound = function(msg) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.message = msg || 'Not Found'; this.statusCode = 404; this.name = "notFound"}util.inherits(NotFound, Error);export.NotFoundError = NotFound;
Of course, we can also extend the abstract Error Type created above to other custom errors:
var notFountError = require('./error').NotFountError; var UserNotFound = function(msg){ this.constructor.super_(msg);}util.inherits(UserNotFound, notFoundError);
Summary
The above is all about the custom error types in Node. js. I hope the content in this article will be helpful for you to learn or use Node. js. If you have any questions, please leave a message. Thank you for your support.