Git Product home page Git Product logo

Comments (5)

krazar avatar krazar commented on July 29, 2024 1

Excuse me for my stupid question but:

 throw new BadRequestError("Works fine, JSON is sent",{some:"data"});

Is it possible to send some custom object in the constructor without rewriting the class HttpError ?

from typescript-rest.

krazar avatar krazar commented on July 29, 2024

👍

For the moment I use your workaround.

from typescript-rest.

thiagobustamante avatar thiagobustamante commented on July 29, 2024

Hi,

Express uses an error handler middleware that is called to process exceptions that are not handled by its routes.

It has a default error handler middleware (see this) that uses a module called finalhandler to process all uncaught errors.

As you can see in the finalhandler documentation, it will always send an HTML page containing the description of the error (the error message) and, if not running in a production environment, a stack trace.

This is not implemented by typescript-rest, but is the default behavior of expressjs itself. So, if we want to override this behavior, we need to provide our own error handler implementation, that would handle the error before it is raised to the express default middleware.

This can be done, as @mrslnv already posted previously, writing something like:

import { HttpError } from 'typescript-rest';
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  if (err instanceof HttpError){
    if (res.headersSent) { // important to allow default error handler to close connection if headers already sent
      return next(err)
    }
    res.set("Content-Type", "application/json")
    res.status(err.statusCode)
    res.json({error : err.message, code: err.statusCode});
  } else {
    next(err);
  }
});

However, the last situation showed by @mrslnv will never work:

@path("dummy2")
@get
dummy2(): Promise {
  return new Promise(function (resolve, reject) {
    setTimeout(()=>{
      throw new BadRequestError("error handling not applied",{some:"data"});
    },1000);
  });
}

That code are not catching the exception and rejecting the promise. The exception will be lost and can not be sent to express error handling. To this code work, it needs to be refactored to something like:

@path("dummy2")
@get
dummy2(): Promise {
  return new Promise(function (resolve, reject) {
    setTimeout(()=>{
      try {
        throw new BadRequestError("error handling not applied",{some:"data"});
      } catch(e) {
        return reject(e);
      }
    },1000);
  });
}

We could create an errorHandler like that one above and register it in typescript-rest library (maybe through some method like Server.useJsonErrorHandler(); or something like this. But I don't know if it is a good idea.

Some people will need to sent a json like:

{ "error": "my message"}

... while others will prefer:

{ "message": "my message", "status": 403}

And so on...

So I think that the most reasonable solution is to allow the developer to specify how he wants to sent his error.... And express already allow it through a custom error handler. So, do you think that it is already necessary to create another method for this?

EDIT
Just to clarify, the first code showed by @mrslnv works because the exception is not occurring asynchronously:

@path("dummy1")
@get
dummy1(): Promise {
  return new Promise(function (resolve, reject) {
    // this is a sync error and will be caught and redirected to the promise reject method
    throw new BadRequestError("Works fine, JSON is sent",{some:"data"});
  });
}

from typescript-rest.

mrslnv avatar mrslnv commented on July 29, 2024

Thanks for extensive explanation!

I agree that it would be enough if this case is discussed and described in the documentation (which is very good).

from typescript-rest.

mate-h avatar mate-h commented on July 29, 2024

How about using JSON.stringify and JSON.parse?

app.use(
      (
        err: any,
        req: express.Request,
        res: express.Response,
        next: express.NextFunction
      ) => {
        if (err instanceof Errors.HttpError) {
          res.set("Content-Type", "application/json");
          res.status(err.statusCode);
          try {
            const parsed = JSON.parse(err.message);
            res.json(parsed);
            return;
          }
          catch (e) {
            res.json({ message: err.message });
            return;
          }
        } else {
          next(err);
        }
      }
    );
throw new Errors.ForbiddenError(JSON.stringify({ message: "Error msg", code: "error-code" }));

from typescript-rest.

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.