1

In order to test how the front-end responds to various HTTP status error codes, I want to intentionally return an Error from one of my front-end service methods to simulate an Error from one of the API endpoints. The question is... how to do it in a more detailed manner.

I tried using the new Error() constructor, but I can see that I just have the option to add a message as argument to the constructor. I would also want to mock a status code, like for example 500.

The question that was pointed as a potential solution, How do I create a custom Error in JavaScript?, does not solve my problem. In the question and answers it is mentioned that the person wants to simply throw a new error with a name and a message, while I would also want to be able to throw different Error codes.

scottheckel
  • 9,106
  • 1
  • 35
  • 47
Iulia Mihet
  • 650
  • 1
  • 10
  • 34
  • 1
    I think you are missing context in your question. It looks like you want to simulate e.g. a http:500 error code, but attempt to use `throw new Error();`. What exactly are you trying to accomplish? – ASDFGerte Jun 21 '19 at 13:33
  • Are you talking about errors, just in the context of frontend or backend? – lealceldeiro Jun 21 '19 at 13:33
  • If just doing a quick manual test, you can hard set a status code via the library you're using to create your API. As a better approach, consider writing tests while mocking API responses. Check out mountebank (http://www.mbtest.org). – Grafluxe Jun 21 '19 at 14:12

1 Answers1

0

You can throw an error with

throw "SimpulatedException";

Depending on the framework you are using (I assume expressjs as it is the most popular) you can also just comment out the actual route an just return an error.

app.get('/', (req, res) => {
    res.status(500) //HTTP Statuscode
    res.json({
        status: 500, //Having the statuscode down in the body is needed for some frameworks.
        msg: "An error, just for testing" //An errormessage to display for the user
    }) //Body
})
Florian sp1rit
  • 575
  • 1
  • 7
  • 20