constructor.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { extendError } from "./extend-error";
  2. import { normalizeArgs, normalizeOptions } from "./normalize";
  3. import { toJSON as errorToJSON } from "./to-json";
  4. const constructor = Ono;
  5. export { constructor as Ono };
  6. /**
  7. * Creates an `Ono` instance for a specifc error type.
  8. */
  9. // eslint-disable-next-line @typescript-eslint/naming-convention
  10. function Ono(ErrorConstructor, options) {
  11. options = normalizeOptions(options);
  12. function ono(...args) {
  13. let { originalError, props, message } = normalizeArgs(args, options);
  14. // Create a new error of the specified type
  15. let newError = new ErrorConstructor(message);
  16. // Extend the error with the properties of the original error and the `props` object
  17. return extendError(newError, originalError, props);
  18. }
  19. ono[Symbol.species] = ErrorConstructor;
  20. return ono;
  21. }
  22. /**
  23. * Returns an object containing all properties of the given Error object,
  24. * which can be used with `JSON.stringify()`.
  25. */
  26. Ono.toJSON = function toJSON(error) {
  27. return errorToJSON.call(error);
  28. };
  29. /**
  30. * Extends the given Error object with enhanced Ono functionality, such as nested stack traces,
  31. * additional properties, and improved support for `JSON.stringify()`.
  32. */
  33. Ono.extend = function extend(error, originalError, props) {
  34. if (props || originalError instanceof Error) {
  35. return extendError(error, originalError, props);
  36. }
  37. else if (originalError) {
  38. return extendError(error, undefined, originalError);
  39. }
  40. else {
  41. return extendError(error);
  42. }
  43. };
  44. //# sourceMappingURL=constructor.js.map