Sunday 8 January 2017

Trying to find good design pattern for handling many different types of errors (mongoose, redis, express) in a REST API

Title says it all. I built and launched my first production API using express, mongoose, and redis a few months ago and one of the things that I was really unhappy with was my error handling code. Right now it just looks and feels like a giant mess. I'm trying to find a way to cleanly organize all of the possible error handling I could want to do, especially when using libraries to utilize various tools like mongoose for mongodb and the node redis module for redis. You can have so many different types of errors, especially with mongoose and needing to validate and sanitize user input from the client. I've been doing research on this subject and the examples I can find are usually way too simple and also it seems that it's very hard for everyone to agree on something.This new API that I am currently working on is not that big, but at the same time it's not just a simple side project so I would like to find a simple and clean way to handle these errors this time. So far the only thing that I think I know for sure, is that I want to have an errors.js file with custom functions or constructor functions that I can funnel all of my errors into when they happen in my middleware or my controllers.I did come across some really good StackOverflow questions in regards to managing mongoose validation errors, but the I'm not sure how valid the answers are or if anything is outdated as things seem to change so rapidly in node:http://ift.tt/2iSeQaR put it simply, I just need a way to handle all types of errors in general, but also a clean way to manage things like validation errors from mongoose, and also general errors when interacting with redis. Right now I have some nasty code in my controllers and middleware and I'd love to find a better way to organize it. I'd also like to be able to end up with a nice json response for the client, that in some cases has a specific error message to show the user eg. signup validation error.I realize there are multiple ways you could handle this, but as someone new to node and building API's, I'd love to hear, even at a high level, how all of you have approached the problems I'm describing and what your solutions look like.As always thanks for the help!

Submitted January 08, 2017 at 07:48PM by m9js

No comments:

Post a Comment