Comments (10)
Hi @markkelsall no worries :)
Error middleware is a special middleware that needs to be registered via ERROR_MIDDLEWARE
token, like so:
import { ErrorMiddleware, ERROR_MIDDLEWARE } from '@decorators/express';
@Injectable()
class ServerErrorMiddleware implements ErrorMiddleware {
public use(error: Error, request: Request, response: Response, next: NextFunction) {
next();
}
}
Container.provide([
{ provide: ERROR_MIDDLEWARE, useClass: ServerErrorMiddleware }
]);
Error middleware is different to other middlewares cause it has error
as a first argument and that's why it's treated a bit differently. Here's the example how to use it in my demo project https://github.com/serhiisol/decorators-server/blob/master/src/middleware/server-error.ts
from node-decorators.
Great, thanks. In your inline example, what is Container? How does it get attached to an express instance? Or is it just a case of having it listed in your middleware stack on a method/controller and it only gets called if there was an error thrown/not handled?
In your demo project, the server error middleware doesn't seem to be referenced?
from node-decorators.
Container is an export from @decorators/di
package that @decorators/express
uses underneath.
Yes error middleware gets called only when error happens. Take a look at the whole repository as a reference.
from node-decorators.
Thanks, I had a closer look at your demo repo and it makes sense that you just set up the middleware but still don't see how the server app instance knows to use it as app and Container don't know about each other?
When pulled your decorators-server repo down, I couldn't get it to run, nor could I make error middleware trigger when I purposefully threw an error in one of my controllers.
from node-decorators.
Here's the app file - https://github.com/serhiisol/decorators-server/blob/master/src/app.ts
import { Container } from '@decorators/di';
import { attachControllers, ERROR_MIDDLEWARE } from '@decorators/express';
import { json, urlencoded } from 'body-parser';
import * as express from 'express';
import * as cors from 'cors';
import { initialize as initializePassport } from 'passport';
import { configurePassport, ServerErrorMiddleware } from './middleware';
import { StatusController, AuthController } from './api';
export function init(): express.Application {
const app: express.Express = express();
configurePassport();
app.use(json());
app.use(urlencoded({ extended: false }));
app.use(initializePassport());
app.use(cors());
Container.provide([
{ provide: ERROR_MIDDLEWARE, useClass: ServerErrorMiddleware }
]);
attachControllers(app, [
StatusController,
AuthController
]);
return app;
}
from node-decorators.
Ok understand how they reference each other now - https://github.com/serhiisol/node-decorators/blob/master/express/src/express.ts#L14
However, it doesn't seem to work for me:
@Controller("/TestDecorator")
export class TestDecoratorController {
@Get("/:id")
getData(@DecoratorResponse() res, @Params("id") id: string): any {
console.log("id", id);
throw new Error("argh");
// res.status(200).send({
// id,
// message: "hello"
// });
}
}
class ServerErrorMiddleware implements ErrorMiddleware {
use(error: Error, request: Request, response: Response, _next: NextFunction) {
console.log("caught this error", error.message);
response.status(200).json({ message: "error" });
}
}
Container.provide([{ provide: ERROR_MIDDLEWARE, useValue: ServerErrorMiddleware }]);
attachControllers(app, [TestDecoratorController]);
I'm expecting the response to the browser to be a json object with the message "error" but I'm just getting the native error being thrown back
from node-decorators.
Yes, based on the snippet above, that should be everything right? However the response is the error that is thrown in the controller rather than error middleware code
from node-decorators.
Hm, must be a bug. I'm going to fix it now.
from node-decorators.
This issue must have appeared with the latest release. With async providers introduced in the latest di package error middleware is applied before handlers. I'll prepare a release in a bit.
from node-decorators.
Pushed new version.
from node-decorators.
Related Issues (20)
- Typescript v5 injection of type undefined HOT 11
- socket decorator not working HOT 1
- TypeError: Cannot read properties of undefined HOT 4
- Decorators with inheritance HOT 4
- Error while inject property in middelwares HOT 6
- Error injection HOT 18
- Where is attachMiddleware o how it change? HOT 2
- Where did the flexibility go?! HOT 11
- @Controller & Rest methods no longer work HOT 1
- Can't attach a controller without an error middleware HOT 17
- HttpModule is not exported HOT 21
- express-session is causing ERR_HTTP_HEADERS_SENT HOT 18
- Decorator error handling
- Missing data, EJS, express-ejs-layouts
- Implement OpenAPI nullable schema property
- Param validation HOT 13
- Which container instance should I use ? HOT 2
- elysia Js HOT 3
- [BUG] Inject() and Injectable() not working as expected - upgrade 2.x -> 3.x HOT 4
- [BUG] dependency injection constructor service initialize fail HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from node-decorators.