Skip to content

Commit

Permalink
Merge feat-add-httpsexceptions-packages
Browse files Browse the repository at this point in the history
  • Loading branch information
Travis committed Apr 19, 2020
2 parents c775637 + 23b6fb4 commit dd0800e
Show file tree
Hide file tree
Showing 161 changed files with 1,657 additions and 104 deletions.
8 changes: 5 additions & 3 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ module.exports = {
{link: "/docs/filters.html", text: "Filters"},
{link: "/docs/interceptors.html", text: "Interceptors"},
{link: "/docs/authentication.html", text: "Authentication"},
{link: "/docs/hooks.html", text: "Hooks"}
{link: "/docs/hooks.html", text: "Hooks"},
{link: "/docs/exceptions.html", text: "Exceptions"},
]
},
{
Expand Down Expand Up @@ -153,14 +154,15 @@ module.exports = {
"filters",
"interceptors",
"authentication",
"request-data-persistence",
"hooks"
"hooks",
"exceptions"
]
},
{
title: "Advanced",
collapsable: false,
children: [
"request-data-persistence",
"injection-scopes",
"custom-providers",
"custom-endpoint-decorators",
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ You can set the response header with the @@Header@@ decorator:

### Throw exceptions

You can use [ts-httpexceptions](https://github.com/TypedProject/ts-httpexceptions) or similar module to throw an http exception.
You can use [@tsed/exceptions](/docs/exceptions.md) or similar module to throw an http exception.
All exception will be intercepted by the [Global error handler](/docs/middlewares/override/global-error-handler.md)
and are sent to the client.

Expand Down
66 changes: 66 additions & 0 deletions docs/docs/exceptions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
meta:
- name: description
content: Documentation over Http Exceptions provided by Ts.ED framework. Use class to throw a standard Http error.
- name: keywords
content: http exceptions ts.ed express typescript node.js javascript decorators jsonschema class models
---
# Http exceptions

Ts.ED http exceptions provide classes to throw standard HTTP exceptions. Theses exceptions can be used on Controller, Middleware or injectable Service.
Emitted exceptions will be handle by the @@GlobalErrorHandlerMiddleware@@ and formatted to an Express response with the right status code and headers.

Other thing. This module can be used with a pure Express application.

## Installation

```bash
npm install @tsed/exceptions
// or
yarn add @tsed/exceptions
```

## Usage

<Tabs class="-code">
<Tab label="Ts.ED">

<<< @/docs/docs/snippets/exceptions/usage-controller.ts

</Tab>
<Tab label="Express.js">

<<< @/docs/docs/snippets/exceptions/usage-express-route.ts

</Tab>
</Tabs>

## Custom exception

It's possible to create your own exception by creating a class which inherit from @@Exception@@ or one of the built-in exception like @@BadRequest@@.

Example:
```typescript
import {BadRequest} from "@tsed/exceptions";

export class IDFormatException extends BadRequest {
constructor() {
super("ID format is not valid");
}
}
```

## Built-in exceptions

### Redirections (3xx)

<ApiList query="module == '@tsed/exceptions' && symbolType === 'class' && path.indexOf('redirections') > -1" />

### Client errors (4xx)

<ApiList query="module == '@tsed/exceptions' && symbolType === 'class' && path.indexOf('clientErrors') > -1" />

### Server errors (5xx)

<ApiList query="module == '@tsed/exceptions' && symbolType === 'class' && path.indexOf('serverErrors') > -1" />

2 changes: 1 addition & 1 deletion docs/docs/middlewares/endpoint-error-middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Then, add your middleware on your endpoint controller's:

```typescript
import {Controller, Get, UseAfter} from "@tsed/common";
import {NotFound} from "ts-httpexceptions";
import {NotFound} from "@tsed/exceptions";

@Controller('/test')
class MyCtrl {
Expand Down
6 changes: 3 additions & 3 deletions docs/docs/middlewares/endpoint-middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ create a middleware to do something on request or response like that:

```typescript
import {IMiddleware, Middleware, Request, Configuration} from "@tsed/common";
import {NotAcceptable} from "ts-httpexceptions";
import {NotAcceptable} from "@tsed/exceptions";

@Middleware()
export class AcceptMimesMiddleware implements IMiddleware {
Expand Down Expand Up @@ -82,7 +82,7 @@ export function AcceptMimes(...mimes: string[]) {
```typescript
// middlewares/accept-mimes.ts
import {IMiddleware, Middleware, EndpointInfo, Endpoint, Request} from "@tsed/common";
import {NotAcceptable} from "ts-httpexceptions";
import {NotAcceptable} from "@tsed/exceptions";

@Middleware()
export default class AcceptMimesMiddleware implements IMiddleware {
Expand Down Expand Up @@ -126,7 +126,7 @@ Here the code of the middleware:
// middlewares/response-view.ts

import {IMiddleware, Middleware, ResponseData, Response, EndpointInfo, Endpoint} from "@tsed/common";
import {InternalServerError} from "ts-httpexceptions";
import {InternalServerError} from "@tsed/exceptions";

@Middleware()
export default class ResponseViewMiddleware implements IMiddleware {
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/middlewares/global-error-middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Create your middleware error:
```typescript
import { NextFunction as ExpressNext, Request as ExpressRequest, Response as ExpressResponse } from "express";
import { IMiddlewareError, MiddlewareError, Request, Response, Next, Err } from "@tsed/common";
import { Exception } from "ts-httpexceptions";
import { Exception } from "@tsed/exceptions";
import { $log } from "ts-log-debug";

@MiddlewareError()
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/middlewares/override/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class MyCtrl {
## Example

```typescript
import {Unauthorized} from "ts-httpexceptions";
import {Unauthorized} from "@tsed/exceptions";
import {IMiddleware, EndpointInfo, Req, Middleware} from "@tsed/common";

@Middleware()
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/snippets/authentication/auth-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EndpointInfo, IMiddleware, Middleware, Req} from "@tsed/common";
import {Forbidden, Unauthorized} from "ts-httpexceptions";
import {Forbidden, Unauthorized} from "@tsed/exceptions";

@Middleware()
export class CustomAuthMiddleware implements IMiddleware {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Controller, Get, PathParams} from "@tsed/common";
import {BadRequest} from "ts-httpexceptions";
import {BadRequest} from "@tsed/exceptions";

@Controller("/calendars")
export class CalendarCtrl {
Expand Down
33 changes: 33 additions & 0 deletions docs/docs/snippets/exceptions/usage-controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {Controller, Get, Inject, PathParams} from "@tsed/common";
import {BadRequest, NotFound} from "@tsed/exceptions";
import {CalendarsService} from "../services/CalendarsService";

@Controller("/calendars")
export class CalendarCtrl {
@Inject()
calendarsService: CalendarsService;

@Get("/:id")
async get(@PathParams("id") id: number) {
if (isNaN(+id)) {
const error = new BadRequest("Not a number");

// Additionally
error.setHeaders({
"x-header": "value"
});

error.errors = [{"message": "ID is not a number"}];

throw(error);
}

const calendar = await this.calendarsService.get(id);

if (!calendar) {
throw new NotFound("Calendar not found");
}

return calendar;
}
}
57 changes: 57 additions & 0 deletions docs/docs/snippets/exceptions/usage-express-route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {BadRequest, Exception, InternalServerError, NotFound} from "@tsed/exceptions";
import * as Express from "express";
import {getCalendar} from "../services/CalendarService";

const app = Express();

app.get("/calendars/:id", async (req: any, res: any, next: any) => {
const {params: {id}} = req;

if (isNaN(+id)) {
const error = new BadRequest("ID is not a number");

// Additionally
error.setHeaders({
"x-header": "value"
});

error.errors = [{"message": "ID is not a number"}];
error.body = "Not a number";

return next(error);
}

try {
const calendar = await getCalendar(res.params.id);

if (!calendar) {
return next(new NotFound("Calendar not found");
}

res.json(calendar);
} catch (origin) {
next(new InternalServerError("Oops! Something is wrong", origin));
}
});


// GlobalHandler middleware catch exception and send response to the client
app.use((err: any, request: any, response: any, next: any) => {
if (err instanceof Exception) {
if (err.errors) { // If errors is provided
response.set({"x-errors": JSON.stringify(err.errors)});
}

if (err.headers) {
response.set(err.headers);
}

if (err.body) { // If a body is provided
return response.status(err.status).json(err.body);
}

return response.status(err.status).send(err.message);
}

next();
});
2 changes: 1 addition & 1 deletion docs/docs/snippets/middlewares/endpoint-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EndpointInfo, IMiddleware, Middleware, Req} from "@tsed/common";
import {NotAcceptable} from "ts-httpexceptions";
import {NotAcceptable} from "@tsed/exceptions";

@Middleware()
export class AcceptMimesMiddleware implements IMiddleware {
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/snippets/middlewares/global-middleware-error.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Err, Middleware, Req, Res} from "@tsed/common";
import {Exception} from "ts-httpexceptions";
import {Exception} from "@tsed/exceptions";
import {$log} from "ts-log-debug";

@Middleware()
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/snippets/middlewares/global-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Constant, IMiddleware, Middleware, Req} from "@tsed/common";
import {NotAcceptable} from "ts-httpexceptions";
import {NotAcceptable} from "@tsed/exceptions";

@Middleware()
export default class GlobalAcceptMimesMiddleware implements IMiddleware {
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/snippets/model/jsonschema.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {JsonSchemesService, OverrideService, ValidationService} from "@tsed/common";
import * as Ajv from "ajv";
import {ErrorObject} from "ajv";
import {BadRequest} from "ts-httpexceptions";
import {BadRequest} from "@tsed/exceptions";

@OverrideService(ValidationService)
export class AjvService extends ValidationService {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Context, Controller, Get, Middleware, Req, UseBefore} from "@tsed/common";
import {Forbidden} from "ts-httpexceptions";
import {Forbidden} from "@tsed/exceptions";

@Middleware()
class AuthTokenMiddleware {
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/custom-validator.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ To do that, you need to create a custom validation service that will inherit fro
In your project, create a new file named `CustomValidationService.ts` and create a class based on this example:

```typescript
import {BadRequest} from "ts-httpexceptions";
import {BadRequest} from "@tsed/exceptions";
import {OverrideService, JsonSchemesService, ValidationService} from "@tsed/common";

@OverrideService(ValidationService)
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/snippets/passport/AcceptRolesMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EndpointInfo, Middleware, Req} from "@tsed/common";
import {Unauthorized} from "ts-httpexceptions";
import {Unauthorized} from "@tsed/exceptions";

@Middleware()
export class AcceptRolesMiddleware {
Expand Down
6 changes: 3 additions & 3 deletions docs/tutorials/throw-http-exceptions.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Throw HTTP Exceptions

You can use [ts-httpexceptions](https://github.com/TypedProject/ts-httpexceptions) or similar module to throw an http exception.
You can use [@tsed/exceptions](/docs/exceptions.md) or similar module to throw an http exception.
All exception will be intercepted by the [Global error handler](/docs/middlewares/override/global-error-handler.md)
and are sent to the client.

Expand All @@ -15,10 +15,10 @@ This example will produce a response with status code 400 and "Not a number" mes

## Create custom exception

It also possible to create your own exception from any Exception of `ts-httpexceptions` and customize the response headers.
It also possible to create your own exception from any Exception of [@tsed/exceptions](/docs/exceptions.md) and customize the response headers.

```typescript
import {BadRequest} from "ts-httpexceptions";
import {BadRequest} from "@tsed/exceptions";
import {IResponseError} from "@tsed/common";

export class RequiredUserName extends BadRequest implements IResponseError {
Expand Down
3 changes: 2 additions & 1 deletion examples/aws/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"@tsed/common": "5.46.0",
"@tsed/core": "5.46.0",
"@tsed/di": "5.46.0",
"@tsed/exceptions": "5.46.0",
"@tsed/swagger": "5.46.0",
"@tsed/testing": "5.46.0",
"@types/swagger-schema-official": "2.0.20",
Expand Down Expand Up @@ -82,4 +83,4 @@
"tslint": "6.1.0",
"typescript": "3.8.3"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as Sinon from "sinon";
import {CalendarsService} from "../../services/calendars/CalendarsService";
import {MemoryStorage} from "../../services/storage/MemoryStorage";
import {CalendarsCtrl} from "./CalendarsCtrl";
import {NotFound} from "ts-httpexceptions";
import {NotFound} from "@tsed/exceptions";

describe("CalendarsCtrl", () => {
describe("get()", () => {
Expand Down
2 changes: 1 addition & 1 deletion examples/aws/src/controllers/calendars/CalendarsCtrl.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {BodyParams, Controller, Delete, Get, PathParams, Post, Put, Required, Status} from "@tsed/common";
import {NotFound} from "ts-httpexceptions";
import {NotFound} from "@tsed/exceptions";
import {Calendar} from "../../interfaces/Calendar";
import {CalendarsService} from "../../services/calendars/CalendarsService";
import {EventsCtrl} from "../events/EventsCtrl";
Expand Down
2 changes: 1 addition & 1 deletion examples/aws/src/controllers/events/EventsCtrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
Required,
Status
} from "@tsed/common";
import {NotFound} from "ts-httpexceptions";
import {NotFound} from "@tsed/exceptions";
import {Event} from "../../interfaces/Event";
import {Task} from "../../interfaces/Task";

Expand Down
2 changes: 1 addition & 1 deletion examples/aws/src/services/calendars/CalendarsService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {$log, Constant, Service} from "@tsed/common";
import {NotFound} from "ts-httpexceptions";
import {NotFound} from "@tsed/exceptions";
import {Calendar} from "../../interfaces/Calendar";
import {MemoryStorage} from "../storage/MemoryStorage";

Expand Down
3 changes: 2 additions & 1 deletion examples/getting-started/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@tsed/common": "5.46.0",
"@tsed/core": "5.46.0",
"@tsed/di": "5.46.0",
"@tsed/exceptions": "5.46.0",
"@tsed/swagger": "5.46.0",
"@tsed/testing": "5.46.0",
"@types/swagger-schema-official": "2.0.20",
Expand Down Expand Up @@ -65,4 +66,4 @@
"tslint": "6.1.0",
"typescript": "3.8.3"
}
}
}
Loading

0 comments on commit dd0800e

Please sign in to comment.