moleculer-web icon indicating copy to clipboard operation
moleculer-web copied to clipboard

500 Status Code for ServiceNotFoundError Using Express Middleware

Open valeeum opened this issue 4 years ago • 5 comments

I'm getting a 500 error code for ServiceNotFoundError while using express in middleware mode(settings.server = false). I experienced this on both 0.9.0 + 0.9.1. Moleculer docs state this should be a 404. Not a big deal but thought I'd point it out.

https://moleculer.services/docs/0.14/errors.html

started() { const app = express(); app.use("/", this.express()); }

valeeum avatar Mar 11 '20 01:03 valeeum

I would like to add that setting mappingPolicy to 'restrict' changes the response to a 404.

valeeum avatar Mar 12 '20 19:03 valeeum

Could you make a reproduce example?

icebob avatar Jul 19 '20 09:07 icebob

I'm having the same issue, using:

    "moleculer": "^0.14.10",
    "moleculer-web": "^0.9.0",

Here's is the sample code:

const { ServiceBroker } = require('moleculer')
const express = require('express')
const ApiService = require('moleculer-web')

const broker = new ServiceBroker({ logger: console })

const svc = broker.createService({
  name: 'api',
  mixins: ApiService,
  settings: {
    server: false
  }
})

const app = express()

app.use('/', svc.express())

app.listen(3000, err => {
  if (err) { return console.error(err) }
})

broker.start()

And when calling a non existent url a 500 is returned instead of a 404.

# curl -I http://localhost:3000/some-nonexistent-url
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
X-Request-ID: 61cb2099-d27d-4275-b09d-ff79ed92f178
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 748
Date: Thu, 05 Nov 2020 20:33:15 GMT
Connection: keep-alive

If I run moleculer-web without express, in middleware mode, the result is as expected (a 404).

pekastel avatar Nov 05 '20 20:11 pekastel

The problem is that Express builtin error-handler doesn't use the err.code in the MoleculerErrors. To convert it, use something similar error handler for Express:

const { ServiceBroker } = require("moleculer");
const { MoleculerError } = require("moleculer").Errors;
const express = require("express");
const ApiService = require('moleculer-web')

const broker = new ServiceBroker({ logger: console });

const svc = broker.createService({
    name: "api",
    mixins: ApiService,
    settings: {
        server: false
    }
});

const app = express();

app.use("/", svc.express());
app.use("/", (err, req, res, next) => {
    if (err instanceof MoleculerError) {
        return res.status(err.code).json(err);
    }
    next(err);
});

app.listen(3000, err => {
    if (err) { return console.error(err); }
});

broker.start();

icebob avatar Nov 06 '20 17:11 icebob

Thanks @icebob! Didn't see this on the docs.

pekastel avatar Nov 09 '20 19:11 pekastel