Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lukasjhan/nestjs-exception-factory
Simple Factory Function for Nestjs Exception
https://github.com/lukasjhan/nestjs-exception-factory
exception javascript nestjs typescript
Last synced: 21 days ago
JSON representation
Simple Factory Function for Nestjs Exception
- Host: GitHub
- URL: https://github.com/lukasjhan/nestjs-exception-factory
- Owner: lukasjhan
- Created: 2023-05-05T06:59:23.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2023-05-05T07:04:38.000Z (over 1 year ago)
- Last Synced: 2024-04-12T05:09:11.422Z (7 months ago)
- Topics: exception, javascript, nestjs, typescript
- Language: TypeScript
- Homepage:
- Size: 7.81 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# NestJS Exception Factory
Simple Factory Function to create NestJS Exceptions.
## Code
```typescript
declare class CustomExceptionProtoType extends HttpException {
constructor();
}export function createException(
status: HttpStatus,
errorCode: string,
message: string
) {
class CustomException extends HttpException {
constructor() {
super({ status, errorCode, message }, status);
Object.setPrototypeOf(this, Object.getPrototypeOf(HttpException));
}
}
return CustomException as unknown as typeof CustomExceptionProtoType;
}
```## Usage
Copy & Paste into your nestjs project. Then use it like this:
```typescript
export const CustomException = createException(
HttpStatus.BAD_REQUEST,
'CUSTOM_ERROR_CODE',
'Custom Error Message'
);function someFunction() {
...
throw new CustomException();
...
}
```## Warning
`Do not import this code as a module. `
`It will not work.`
Becasue behaviour of `instanceof` operator, is that the class must be exactly in the parent chain, in the sense of JavaScript object reference. Hence, if you import `HttpException` class twice, they are different actual object references, and instanceof may give a "false" negative.
In NestJS, checking exception type is done by `instanceof` operator. So, if you import this code as a module, it will not work.