Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/yeliex/exception-js
Javascript exception class with ts for both server-side and clients
https://github.com/yeliex/exception-js
Last synced: about 2 months ago
JSON representation
Javascript exception class with ts for both server-side and clients
- Host: GitHub
- URL: https://github.com/yeliex/exception-js
- Owner: yeliex
- License: mit
- Created: 2019-09-12T07:18:15.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2024-09-29T07:42:20.000Z (3 months ago)
- Last Synced: 2024-11-07T23:36:59.771Z (about 2 months ago)
- Language: TypeScript
- Homepage:
- Size: 91.8 KB
- Stars: 1
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# exception-js
Javascript exception with ts for both server-side and clients
## Installation
```bash
npm install exception-js --save
# OR
yarn add exception-js
```## Usage
```typescript
import * as Exceptions from 'exception-js';app.use('/not_found', async () => {
throw new Exceptions.NotFound();
});
```### Create Exception Instance
```typescript
const error = new Exceptions.NotFound();// error.code => 404
// error.name => NotFound
// error.subcode => 0
// error.message => Not Found
```### Create Exception Instance With Custom Message
```typescript
const error = new Exceptions.NotFound('resource not found');// error.code => 404
// error.message => resource not found
```### Create Exception Instance With Custom MetaData
```typescript
const error = new Exceptions.NotFound('resource not found', {
requestId: 'xxxxxx',
});// error.code => 404
// error.message => resource not found
// error.meta => { requestId: 'xxxxxx' }
```### toJSON
```typescript
const error = new Exceptions.NotFound('resource not found', {
requestId: 'xxxxxx',
});console.log(error.toJSON());
// {
// code: 404,
// subcode: 0,
// message: 'resource not found',
// meta: {
// requestId: 'xxxxxx'
// }
// }
```### Define Custom Exception
```typescript
import { define } from './exception';const BusinessException = define<'BusinessException'>('BusinessException', {
code: 500,
subcode: 1,
message: 'something went wrong', // default message
meta: { // default meta info
api: 'xxx'
}, // default
})
```## API Reference
### Exception
```typescript
interface ExceptionBaseProps {
code?: number;
subcode?: number;
meta?: T;
}interface ExceptionDefination extends ExceptionBaseProps {
message?: string;
}declare const define: (name: T, define: ExceptionDefination = {}) => typeof Exception
declare class Exception extends Error {
constructor(message?: string, meta?: U)readonly name: T;
readonly code: number;
readonly subcode: number;
readonly meta: U;toJSON(): {
code: number;
subcode: number;
message: string;
meta: U;
}
}
```