Analysis of custom error types under Node.js

不言
Release: 2018-06-30 14:40:40
Original
2342 people have browsed it

This article introduces in detail how to customize error types under Node.js. It has certain reference value for everyone to learn or use Node.js. Friends in need can refer to it. Let’s take a look together. Take a look.

Preface

Generally speaking, few people will consider the strategy of how to deal with errors generated by applications. During the debugging process, simply Usingconsole.log('error')to locate errors is basically enough. By leaving this debugging information, it can save us a lot of time in the future debugging process and improve maintainability. So error messages are very important. At the same time, it will also bring about some bad usage. Custom error types have been used in recent projects, and I felt it was necessary to learn more about them, so I wrote this article to facilitate myself and everyone in need to refer to them when needed.

Subclassing Error

First we can define a subclass of Error. It is easy to achieve throughObject.createandutil.inherits:

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);
Copy after login

can be achieved throughinstanceofTo check the error type and perform different processing according to the type.

The above code sets the built-inmessage, anderroris an instance ofNotFoundandError, But notRangeError.

If you use theexpressframework, you can set otherpropertiesto makeerrormore useful.

For example, when handling an HTTP error, you can write it like this:

function NotFound(msg) { Error.call(this); this.message = msg; this.statusCode = 404; }
Copy after login

Now You can already handle error messages through error handling middleware:

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); });
Copy after login

This will send the HTTP status code to the browser, when ## When thestatusCodeof #erris not set or equals 500, this error will be sent via email. This will eliminate those 404, 401, 403, etc. errors.

Read

console.error(err.stack)In fact, it will not work as expected. Like node, chrome based on V8 can useError.captureStackTrace(this, arguments.callee)error constructor for stack tracing.

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;
Copy after login

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);
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Introduction to module definition in nodejs

nodejs method to implement bigpipe asynchronous loading of pages

About node.js method of reading and writing system files and directories based on the fs module

The above is the detailed content of Analysis of custom error types under Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!