fmvilas / swagger-node-codegen

An OpenAPI 3.x/Swagger 2 code generator for Node.js
Apache License 2.0
200 stars 55 forks source link

Service template shouldn't advise the user to return an error object #43

Closed david-shepard closed 5 years ago

david-shepard commented 5 years ago

It doesn't look like this works https://github.com/fmvilas/swagger-node-codegen/blob/master/templates/express-server/src/api/services/___.js#L27-L30

 // throw new Error({
  //   status: 500, // Or another error code.
  //   error: 'Server Error' // Or another error message.
  // });

the caller of the function expects an Error object with fields status & error, but this doesn't do that since the Error constructor doesn't take an object - it expects a string https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error. You should be able to do

// throw {
  //   status: 500, // Or another error code.
  //   error: 'Server Error' // Or another error message.
  // };
fmvilas commented 5 years ago

Good catch! Mind a PR? I'm very busy lately and don't have time to maintain these packages. BTW, you might want to have a look at https://github.com/fmvilas/openapi3-generator which has the same problem, but it's highly customizable.

david-shepard commented 5 years ago

Sure, I was also toying around with ES6 syntax and found out you can easily implement a custom error class like

class CustomError extends Error {
  constructor (...args) {
    super(...args);
    Error.captureStackTrace(this, CustomError);
    this.status = args[0].status;
    this.error = args[0].error;
  }
}

and then you could do

// throw new CustomError({
  //   status: 500, // Or another error code.
  //   error: 'Server Error' // Or another error message.
  // });

this way it's still an Error object and you get the stacktrace

fmvilas commented 5 years ago

I like it much better 👍