# cast-error

> cast Error for use in TypeScript in catch clausule

Latest version **0.1.7** (published 2026-10-22) · 0 weekly downloads

## Install

```sh
npm install cast-error
pnpm add cast-error
yarn add cast-error
bun add cast-error
```

## Health

**Score 65/100 (B)** — status: active.

Positive: has types; no vulnerabilities; has provenance; recently updated; high maintenance score.

Warnings: low downloads; no esm support; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.1.7 |
| Published | 2026-10-22 |
| First published | 2021-10-22 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 59.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 0 |
| Maintainers | tute |

## Links

- npm: https://www.npmjs.com/package/cast-error
- Repository: https://github.com/codenautas/cast-error
- Homepage: https://github.com/codenautas/cast-error#readme
- Issues: https://github.com/codenautas/cast-error/issues
- npm.io page: https://npm.io/package/cast-error

## Recent versions

- 0.1.7 (latest) — 2026-10-22
- 3.0.0-beta.1 (beta) — 2026-05-24
- 0.1.6 — 2026-10-17
- 0.1.5 — 2026-07-26
- 0.1.4 — 2026-06-23
- 0.1.3 — 2026-01-31
- 0.1.2 — 2025-06-22
- 0.1.1 — 2024-02-18
- 0.1.0 — 2021-11-18
- 0.0.7 — 2021-11-10
- 0.0.6 — 2021-10-27
- 0.0.5 — 2021-10-23
- 0.0.4 — 2021-10-23
- 0.0.3 — 2021-10-22

## README

# cast-error

cast Error for use in TypeScript in catch clause


[![npm-version](https://img.shields.io/npm/v/cast-error.svg)](https://npmjs.org/package/cast-error)
[![downloads](https://img.shields.io/npm/dm/cast-error.svg)](https://npmjs.org/package/cast-error)
[![build](https://github.com/codenautas/cast-error/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/codenautas/cast-error/actions/workflows/build-and-test.yml)
[![coverage](https://img.shields.io/coveralls/codenautas/cast-error/master.svg)](https://coveralls.io/r/codenautas/cast-error)
[![sonar](https://sonarcloud.io/api/project_badges/measure?project=codenautas_cast-error&metric=alert_status)](https://sonarcloud.io/summary/overall?id=codenautas_cast-error)
[![qa-control](https://github.com/codenautas/cast-error/actions/workflows/qa-control.yml/badge.svg)](https://github.com/codenautas/cast-error/actions/workflows/qa-control.yml)


language: ![English](https://raw.githubusercontent.com/codenautas/multilang/master/img/lang-en.png)
also available in:
[![Spanish](https://raw.githubusercontent.com/codenautas/multilang/master/img/lang-es.png)](LEEME.md)


## Install


```sh
$ npm install cast-error
```


## Main goal

The main goal is to have handy way to receive typed Errors y _Typescript_.

In one hand in _Typescript_ when you use `catch(err)` the variable
`err` is of type `unknown` (formerly `any`). That's why you cannot
write `err.code` for `SystemErrors` (formerly you can but `tsc`
did not warn you if you make a typo like `err.code_num`)

In the other hand in _Javascript_ you can throw any variable
regardless of its type. You can even throw `null`. Then it isn't
safe to write `err.message`.

With **cast-error** this problems are solved in a fancy and efficient
way.

Instead of writing this:


![try{ somethingCanGoWrong(); }catch(err){ console.error(err.message || err.toString()); throw err; } try{ await fsPromise.unlink('/tmp/aFile.txt'); }catch(err){ if(err.code!='ENOENT') throw err; }](doc/catchjs.png)


with **cast-error** you can write:


```ts
try{
    somethingCanGoWrong();
}catch(err){
    var error = castError.unexpected(err); // implicit console.err because is unexpected
    throw err;
}

try{
    await fsPromise.unlink('/tmp/aFile.txt');
}catch(err){
    var error = castError.expected(err)
    if(error.code!='ENOENT') throw err;  // code exists in error because is a SystemError
}
```


# Getting deep


## Use cases

The main use cases of `try/catch` are:

   1. To register unexpected error conditions in a way that the programmers
   can later identify and correct the bug.
   2. To warn the users that there is a problem with their input data.
   3. To handle an exceptional and recoverable situation.


### Case 1: logging unexpected errors

It is possible to hook and centralize the way to log error in every `catch`
setting the log function with `setLogFunction` and then call `unexpected`
in the main cycle and in all points where special behavior is needed.


```ts

function initializeSystem(){
    //... other inits...
    var attributes = {code:true,err_num:true,cause:true};
    type MyGlobalError = Error & {[k in keyof typeof attributes]: any}
    castError.setLogFunction(function(context:string, error:MyGlobalError){
        console.log('***********',context);
        var attr: keyof typeof attributes;
        for(attr in attributes){
            console.log(attr,':',error[attr])
        }
    })
}

// In  the main cycle
catch(err){
    throw castError.unexpected(err);
}

// In a function with special needs:
function getStream(name:string){
    try{
        const fd = await fs.open(name)
        var stream = fd.createReadStream()
        this.decorateStream(stream);
        return stream;
    }catch(err){
        var error = unexpected(err)
        console.log('opening stream',name,'in',this.context(error));
        throw error;
    }
}

```


### Case 2: Warning users that there is a problem with their input data.

In some cases, we need to warn users if there are problemas with their input data.
For example, if the user wants to delete a file, and the system doesn't find the file it must warn the user.

In Node.js `fs.exists` is deprecated. In the [documentation](https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fsexistspath-callback)
is clear that the way is to use the file and capture the error to know if
the file was not found:


```ts
import * as fs from 'fs/promises';
import {expected} from 'cast-error';

function openFileAndProcess(filename:string){
    try{
        var stream = fs.createReadStream(filename)
        var result = process(stream);
        return result;
    }catch(err){
        var error = expected(err);
        if(error.code=='ENOENT'){
            return {
                ok:false,
                message:'file not found'
            }
        }
        throw error;
    }
}
```


There are many caveats to observe:
   1. If the system is a typical web application is reasonable to think that
   there is a table with the names of the files that can be delete by the user.
   If opening (or deleting) a file that is suppose to exists, any error is
   an unexpected error. And, because of that, is part of the Case 1.
   2. Not all programs are the typical web application. A program can be
   a command line one or an administration web application. In these cases,
   the _file table_ may be not exists.
   3. In any case if it is a web application is mandatory to take care of
   attackers. So in the error messages the system shouldn't send more
   information that what the user can know.
   4. If there no validations to a whitelist there be other validations:
   the folder, the type of file (or its extension), and the logical ownership of the file.


### Caso 3: To handle an exceptional and recoverable situation.

_[... in progress ...]_




## Type system


```ts
```


## License


[MIT](LICENSE)

---
_Source: https://npm.io/package/cast-error · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
