Skip to content

Commit

Permalink
feat: error/ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Apr 3, 2019
1 parent 4d6b899 commit d5c8a30
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,18 @@ isError(new Error()); // true
isError({ mesage: "Fake error" }); // false
```

##### `error/ensure`

If given argument is an error object, it is returned back. Otherwise `TypeError` is thrown.

```javascript
const ensureError = require("type/error/ensure");

const someError = new Error("Some error");
ensureError(someError); // someError
ensureError({ mesage: "Fake error" }); // Thrown TypeError: [object Object] is not an error object
```

### Tests

$ npm test
Expand Down
9 changes: 9 additions & 0 deletions error/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"use strict";

var resolveException = require("../lib/resolve-exception")
, is = require("./is");

module.exports = function (value/*, options*/) {
if (is(value)) return value;
return resolveException(value, "%v is not an error object", arguments[1]);
};
20 changes: 20 additions & 0 deletions test/error/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"use strict";

var assert = require("chai").assert
, ensureError = require("../../error/ensure");

describe("error/ensure", function () {
it("Should return input value", function () {
var value = new Error();
assert.equal(ensureError(value), value);
});
it("Should crash on invalid value", function () {
try {
ensureError(null);
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.name, "TypeError");
assert(error.message.includes("is not an error object"));
}
});
});

0 comments on commit d5c8a30

Please sign in to comment.