Giter Club home page Giter Club logo

Comments (10)

serhiisol avatar serhiisol commented on September 22, 2024

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.

markkelsall avatar markkelsall commented on September 22, 2024

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.

serhiisol avatar serhiisol commented on September 22, 2024

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.

markkelsall avatar markkelsall commented on September 22, 2024

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.

serhiisol avatar serhiisol commented on September 22, 2024

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.

markkelsall avatar markkelsall commented on September 22, 2024

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.

markkelsall avatar markkelsall commented on September 22, 2024

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.

serhiisol avatar serhiisol commented on September 22, 2024

Hm, must be a bug. I'm going to fix it now.

from node-decorators.

serhiisol avatar serhiisol commented on September 22, 2024

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.

serhiisol avatar serhiisol commented on September 22, 2024

Pushed new version.

from node-decorators.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.