All files / fs / _map_error.ts

100.00% Branches 0/0
42.11% Lines 8/19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
 
x37
 
 
 
 
 
x148
 
 
 
 
x148
 
x37
x37
x37
x37
x37
 
 
 
 
 
 
 
 
 



























// Copyright 2018-2025 the Deno authors. MIT license.

import * as errors from "./unstable_errors.js";

type Class<T> = new (...params: unknown[]) => T;

type ClassOrT<T> = T extends Class<infer U> ? U : T;

function mapper(Ctor: typeof errors[keyof typeof errors]) {
  return (err: Error) =>
    Object.assign(new Ctor(err.message), {
      stack: err.stack,
    }) as unknown as ClassOrT<typeof Ctor>;
}

const map: Record<string, ReturnType<typeof mapper>> = {
  EEXIST: mapper(errors.AlreadyExists),
  ENOENT: mapper(errors.NotFound),
  EBADF: mapper(errors.BadResource),
};

function isNodeErr(e: unknown): e is Error & { code: string } {
  return e instanceof Error && "code" in e;
}

export function mapError<E>(e: E) {
  if (!isNodeErr(e)) return e;
  return map[e.code]?.(e) || e;
}