Merge pull request #237 from sbernaldev/patch-1

Use ES6 async/await in the example
This commit is contained in:
Yoni Goldberg
2018-09-16 22:21:03 +03:00
committed by GitHub

View File

@ -1,78 +1,82 @@
# Use only the built-in Error object # Use only the built-in Error object
### One Paragraph Explainer ### One Paragraph Explainer
The permissive nature of JS along with its variety code-flow options (e.g. EventEmitter, Callbacks, Promises, etc) pushes to great variance in how developers raise errors some use strings, other define their own custom types. Using Node.js built-in Error object helps to keep uniformity within your code and with 3rd party libraries, it also preserves significant information like the StackTrace. When raising the exception, its usually a good practice to fill it with additional contextual properties like the error name and the associated HTTP error code. To achieve this uniformity and practices, consider extending the Error object with additional properties, see code example below The permissive nature of JS along with its variety code-flow options (e.g. EventEmitter, Callbacks, Promises, etc) pushes to great variance in how developers raise errors some use strings, other define their own custom types. Using Node.js built-in Error object helps to keep uniformity within your code and with 3rd party libraries, it also preserves significant information like the StackTrace. When raising the exception, its usually a good practice to fill it with additional contextual properties like the error name and the associated HTTP error code. To achieve this uniformity and practices, consider extending the Error object with additional properties, see code example below
### Code Example doing it right ### Code Example doing it right
```javascript ```javascript
// throwing an Error from typical function, whether sync or async // throwing an Error from typical function, whether sync or async
if(!productToAdd) if(!productToAdd)
throw new Error("How can I add new product when no value provided?"); throw new Error("How can I add new product when no value provided?");
// 'throwing' an Error from EventEmitter // 'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter(); const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!')); myEmitter.emit('error', new Error('whoops!'));
// 'throwing' an Error from a Promise // 'throwing' an Error from a Promise
return new Promise(function (resolve, reject) { const addProduct = async (productToAdd) => {
return DAL.getProduct(productToAdd.id).then((existingProduct) => { try {
if(existingProduct != null) const existingProduct = await DAL.getProduct(productToAdd.id);
reject(new Error("Why fooling us and trying to add an existing product?")); if (existingProduct !== null) {
}); throw new Error("Product already exists!");
}); }
``` } catch (err) {
// ...
### Code example Anti Pattern }
}
```javascript ```
// throwing a string lacks any stack trace information and other important data properties
if(!productToAdd) ### Code example Anti Pattern
throw ("How can I add new product when no value provided?");
``` ```javascript
// throwing a string lacks any stack trace information and other important data properties
### Code example doing it even better if(!productToAdd)
throw ("How can I add new product when no value provided?");
```javascript ```
// centralized error object that derives from Nodes Error
function AppError(name, httpCode, description, isOperational) { ### Code example doing it even better
Error.call(this);
Error.captureStackTrace(this); ```javascript
this.name = name; // centralized error object that derives from Nodes Error
//...other properties assigned here function AppError(name, httpCode, description, isOperational) {
}; Error.call(this);
Error.captureStackTrace(this);
AppError.prototype.__proto__ = Error.prototype; this.name = name;
//...other properties assigned here
module.exports.AppError = AppError; };
// client throwing an exception AppError.prototype.__proto__ = Error.prototype;
if(user == null)
throw new AppError(commonErrors.resourceNotFound, commonHTTPErrors.notFound, "further explanation", true) module.exports.AppError = AppError;
```
// client throwing an exception
### Blog Quote: "I dont see the value in having lots of different types" if(user == null)
throw new AppError(commonErrors.resourceNotFound, commonHTTPErrors.notFound, "further explanation", true)
From the blog, Ben Nadel ranked 5 for the keywords “Node.js error object” ```
>…”Personally, I dont see the value in having lots of different types of error objects JavaScript, as a language, doesnt seem to cater to Constructor-based error-catching. As such, differentiating on an object property seems far easier than differentiating on a Constructor type… ### Blog Quote: "I dont see the value in having lots of different types"
### Blog Quote: "A string is not an error" From the blog, Ben Nadel ranked 5 for the keywords “Node.js error object”
From the blog, devthought.com ranked 6 for the keywords “Node.js error object” >…”Personally, I dont see the value in having lots of different types of error objects JavaScript, as a language, doesnt seem to cater to Constructor-based error-catching. As such, differentiating on an object property seems far easier than differentiating on a Constructor type…
> …passing a string instead of an error results in reduced interoperability between modules. It breaks contracts with APIs that might be performing `instanceof` Error checks, or that want to know more about the error. Error objects, as well see, have very interesting properties in modern JavaScript engines besides holding the message passed to the constructor… ### Blog Quote: "A string is not an error"
Blog Quote: “All JavaScript and System errors raised by Node.js inherit from Error”
From the blog, devthought.com ranked 6 for the keywords “Node.js error object”
### Blog Quote: "Inheriting from Error doesnt add too much value"
> …passing a string instead of an error results in reduced interoperability between modules. It breaks contracts with APIs that might be performing `instanceof` Error checks, or that want to know more about the error. Error objects, as well see, have very interesting properties in modern JavaScript engines besides holding the message passed to the constructor…
From the blog machadogj Blog Quote: “All JavaScript and System errors raised by Node.js inherit from Error”
> …One problem that I have with the Error class is that is not so simple to extend. Of course, you can inherit the class and create your own Error classes like HttpError, DbError, etc. However, that takes time and doesnt add too much value unless you are doing something with types. Sometimes, you just want to add a message and keep the inner error, and sometimes you might want to extend the error with parameters, and such… ### Blog Quote: "Inheriting from Error doesnt add too much value"
### Blog Quote: "All JavaScript and System errors raised by Node.js inherit from Error" From the blog machadogj
From Node.js official documentation > …One problem that I have with the Error class is that is not so simple to extend. Of course, you can inherit the class and create your own Error classes like HttpError, DbError, etc. However, that takes time and doesnt add too much value unless you are doing something with types. Sometimes, you just want to add a message and keep the inner error, and sometimes you might want to extend the error with parameters, and such…
> …All JavaScript and System errors raised by Node.js inherit from, or are instances of, the standard JavaScript Error class and are guaranteed to provide at least the properties available on that class. A generic JavaScript Error object that does not denote any specific circumstance of why the error occurred. Error objects capture a “stack trace” detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.All errors generated by Node.js, including all System and JavaScript errors, will either be instances of or inherit from, the Error class… ### Blog Quote: "All JavaScript and System errors raised by Node.js inherit from Error"
From Node.js official documentation
> …All JavaScript and System errors raised by Node.js inherit from, or are instances of, the standard JavaScript Error class and are guaranteed to provide at least the properties available on that class. A generic JavaScript Error object that does not denote any specific circumstance of why the error occurred. Error objects capture a “stack trace” detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.All errors generated by Node.js, including all System and JavaScript errors, will either be instances of or inherit from, the Error class…