Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proper error handling and responses by controllers #61

Open
dsessler7 opened this issue Apr 1, 2022 · 1 comment
Open

Proper error handling and responses by controllers #61

dsessler7 opened this issue Apr 1, 2022 · 1 comment

Comments

@dsessler7
Copy link
Contributor

I initially thought that if you send a response in Express that it would return from the function, but that is incorrect. I was therefore getting errors in certain circumstances where it was complaining that I was trying to set headers that have already been sent (essentially, the code was trying to send multiple responses to one request). Unfortunately, the bad example that I set was also followed by teammates in other routes.

We need to go through our controllers and make sure that responses are only sent in one place for each route and that if an error occurs earlier in the code, that it is thrown/handled properly. I briefly looked into this and it sounds like if an error is thrown in a synchronous function, Express will catch the error automatically. However, if an error is thrown in an asynchronous function, you must pass the error to the next function.

From there, the error is sent to an error handler. If a custom error handler is not created, the error will go to the default error handler, which will essentially pass along the error message and set the status to 500 (unless the error also provides a status code) and send the response to the user.

At the very least we should be passing our errors to next and letting the default error handler do its thing. We might also consider writing our own custom error handlers.

@MFatigati
Copy link
Contributor

I started remedying this situation, along the following lines:

  1. Created an HttpError class under a new models directory that we can use to pass along custom errors.
  2. Created a custom error handler at the end of index.js, that either uses the statuses and messages we set on the HttpError object, or sends an unknown error.
  3. Modified the main functions I was mostly responsible for by, in the catch statements, logging the error (for development), and passing a custom HttpError along to next with a relevant message and status code (for the clients).

I didn't add custom error handling to every helper function because, I think, that will be caught by the main functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants