What is the advantage of using express error handler? - express

What is the advantage of using express error handler instead of handling the errors on the routes as they come as shown below. I am starting an open source project and I wanted to go with the best practices.
register: async function(req, res, next, error ){
User.findOne({username: req.body.username}, async function(err, __user){
try {
if(__user)
throw (
{
"type":"Registration Error",
"details" : `The username "${__user.username}" is already taken. Try another one.`
}
)
} catch(err) {
return res.status(500).json( {"error":{"type":err.type, "details":err.details}} )
}
Are there scenarios where it is better to use one way over the other?
To see the code above in its full context click here

From this article there are definately benefits of using express error handler.
For instance:
you can manage all your errors from one place
You write less code.
You can group errors and manage them depending on their types.
You can get more info from the article. :)

Using the built-in error handler in Express has a number of benefits:
It centralizes error handling in a single place, which makes it easier to maintain and update your error handling logic.
It allows you to handle errors in a consistent way throughout your application, rather than having to repeat error handling logic in multiple places.
It can help improve the readability and maintainability of your code by abstracting the error handling logic away from the main route handling logic.
In essence, instead of having try/catch and repeated return res.status(500).json() logic all throughout your routes, you handle errors in one place and only have to throw in said routes.

Related

Express middleware to conditionally change response result

What I want to achieve is when an express handler fails either by throwing an unhandled exception or returning an empty response like undefined or [], I want the handler to return a predefined mock response rather than failing. This means my server never fails as it either returns the normal real data or predefined mock data.
Of course I will only turn this on in development environment and never in production.
I think a middleware is ideal because I don't want to pollute every handler logic by injecting the response check.
Is this possible with a middleware in express?
If not, what's a cleaner way of achieving this?
The return value of a middleware handler is irrelevant, because a middleware handler is asynchronous by nature. It does one of three things:
It completes the response by calling res.end(...) or similar.
It reports an error by calling next(err).
It delegates the decision to the next middleware by calling next().
Errors can be caught with an additional error-handling middleware, and exceptions can be converted into errors as discussed in [ExpressJs]: Custom Error handler do not catch exceptions.
However, you cannot change a response after it has been sent. Moreover, you write
an express handler fails ... by ... returning an empty response
but an empty response is not a failure. If you want to treat empty responses as failures, but only in production, I suggest that you handle them as special errors. Instead of responding with res.json([]), say, you write next({emptyResponse: []}) and have special error-handling middleware in development only to handle these:
app.use(function(err, req, res, next) {
if (err.emptyResponse) {
console.error(err.emptyResponse);
res.end("Mock response");
} else next(err); // delegate to the standard error handler
});
Perhaps there is a misconception what a response is. The server streams the response to the client, only the client can "get" the response in this sense. Responses cannot be passed between middlewares.

What's the best way to write synchronous code using async libraries

I've been asked to help write some server-side scripts that update calendars, contacts, e-mail and other company services from other internal services for compliance reasons. The code needs to access the LDAP server, an SQL database and e-mail server, compile and merge information in a peculiar way and then go through information in the calendars, contacts and update those depending on what's there and in the LDAP/SQL databases. This needs to be done a couple of times a day, so performance isn't particularly important.
I wanted to try to use node.js for this and after spending a few days with it, I'm having second thoughts as to whether node.js is the right tool to do this. I'm an old school programmer, have C, C++, Unix, SQL, LDAP, TCP/IP in my small finger but I've learned JavaScript/Node.js in a few days out of curiosity.
I use LDAP, SQL and CalDav/CardDAV modules from npm. These are based on Promises.
Thanks to promises, the code is super ugly, unreadable and buggy if there's any kind of network problem. Things that are very easy in classic language such as C or Java are suddenly a massive headache, such as the fact that (say) LDAP information will arrive at a later stage, but there's no point in async operations as nothing can be done in parallel while waiting for those. This pattern repeats itself throughout the code - async operations complicating matters incredibly for zero benefit. It's incredibly difficult to calculate any sort of aggregate values and apply them elsewhere when using these async functions.
My question is this: is there a simple way to invoke async functions that will simply return the value instead of invoking callbacks?
in javascript - no. Waiting async call to complete would block the only thread and so would stop all the work, and so such waiting is not implemented.
But there exists async/await mechanism - syntactic sugar over asynchronous calls, which mimics synchronous calls.
First of all, the vast majority of I/O calls in Node.js are asynchronous. So if you're totally uncomfortable with this, it may not be the right fit for what you're doing.
It is a (IMHO) brilliant language, and you'll find it more comfortable to use as you get used to it.
However, you can write code using Promises that looks very much like synchronous code using the async/await syntax. I find this much easier to deal with compared to using lot's of .thens and .catch.
You can also use try and catch in this context and it will work as you would expect.
This makes for much cleaner, more readable code.
Most Node.js modules support Promises, for those that don't you can often convert functions to returning a Promise rather than expecting a callback to be passed.
NB: Don't forget to await calls to async. functions. I find this is one of the most common errors one makes when using this syntax.
For example:
function callApi() {
return new Promise(resolve => setTimeout(() => resolve({ status: 'ok'}), 500))
}
async function testApi() {
try {
console.log("callApi: Calling function...");
let result = await callApi();
console.log("callApi result:", result);
} catch (err) {
console.error("callApi: Error:", err.message);
}
}
testApi();
Then a further example to show catching an error (say the api fails for some reason):
function callApi() {
return new Promise((resolve, reject) => setTimeout(() => reject(new Error("Api error")), 500))
}
async function testApi() {
try {
console.log("callApi: Calling function...");
let result = await callApi();
console.log("callApi result:", result);
} catch (err) {
console.error("callApi: Error:", err.message);
}
}
testApi();

NServiceBus UnitOfWork to swallow certain exceptions and avoid message failure

I have an interesting use case where certain exception types mean "This message is no longer valid and should be ignored" but this code doesn't have any awareness of the Bus in order to call Bus.DoNotContinueDispatchingCurrentMessageToHandlers().
I loathe boilerplate code like try/catch blocks that need to be present in every single message handler. So I started implementing a UnitOfWork to handle and swallow the exception, but I can't find a way to tell the framework that "Yes, this code generated an exception, but forget about that and just complete the transaction."
Bus.DoNotContinueDispatchingCurrentMessageToHandlers() does not work. I tried having an ITransport injected and calling AbortHandlingCurrentMessage() but that caused the entire universe to blow up. Even stepping through the source code I seem to be at a loss.
Note that it very well may be that this is a horrible idea, because faking that there is no exception when there is in fact an exceptional case would cause the transaction to commit, causing who knows how many bad unknown side effects. So it would be preferable to have a method that still rolls back the transaction but discards the message. But I would be interested in a potential "Yes I know what I'm doing, commit the transaction regardless of the exception" option as well.
As of NServiceBus version 4.4 you can control this by injecting a behavior into our handler pipeline.
This let's you control which exceptions to mute.
class MyExceptionFilteringBehavior : IBehavior<HandlerInvocationContext>
{
public void Invoke(HandlerInvocationContext context, Action next)
{
try
{
//invoke the handler/rest of the pipeline
next();
}
//catch specific exceptions or
catch (Exception ex)
{
//modify this to your liking
if (ex.Message == "Lets filter on this text")
return;
throw;
}
}
There are several samples of how this works:
http://docs.particular.net/samples/pipeline/
That said I totally agree with Ramon that this trick should only be used if you can't change to design to avoid this.
A dirty solution would be having a unit of work test the exception, put the message id in a shared 'ignore' bag (concurrent dictionary in memory, db, what works for you) , let it fail so that everything is rolled back, in the retry have a generic message handler compare the message ID and let that call Bus.DoNotContinueDispatchingCurrentMessageToHandlers()
If you do not want to work with a unit of work then you could try to use the AppDomain.FirstChanceException.
I wouldn't advice any of these as good solution :-)
Why would you like to 'swallow' unhandled exceptions?
If you want to ignore an exception then you should catch these in the handler and then just return and log this.
What I'm more interested in is what about state? You maybe have already writen to a store. Shouldn't these writes be rolled back? If you swallow an exception the transaction commits.
It seems to me you are running in a kind of 'at least once delivery' environment. THen you need to store some kind of message id somewhere.
Or is it an action initiated by several actors based on a stale state? In that case you need to have first/last write wins construction that just ignores a command based on a stale item.
If you handl an event then swallowing a exception seems not correct. They usually say that you can ignore commands but that you always have to handle events.
Shouldn't this be part of validation? If you validate a command then you can decide to ignore it.

In mule, how to validate the params and return with error code and message?

I developed a rest service by mule, and I want to validate the input params, throws exception when the params is invalid, and the error handler could catch the exception(a custom exception with error code and message included) and get the error code and message which i could return to client.
Currently I use the choice router to evaluate expression, and set the error expression. I think it's awkward, and inconvenient.
I read the document, seems there is no such example, so what's the best way to handle the situation?
If you go beyond a trivial REST resource, using choice routers won't cut it.
You have two better options:
Use JAX-RS + Jersey module: http://www.mulesoft.org/documentation/display/current/Jersey+Module+Reference
Use APIkit: http://www.mulesoft.org/documentation/display/current/APIkit
The former is based on a standard, the latter is proprietary. In the future, the latter will receive most of MuleSoft's attention.

Is there a way to change HttpWebRequest behavior on 400/500 status codes?

I am working on building a fluent REST client interface on top of the HttpWebRequest/HttpWebResponse types in .NET. So far, so good...however I am trying to develop a pluggable security framework that can automatically handle security token negotiation, token refreshes, etc.
I've run into a problem due to the nature of how HttpWebRequest/Response work when they encounter a 400 series or 500 series HTTP status code. Rather than simply setting the .StatusCode and .StatusDescription properties and allowing you to handle in whatever way you wish, they throw a WebException. Generally speaking, this probably isn't a problem...however the way we are authenticating (derivative of OAuth 2.0), I need to handle certain 400 series errors without an exception occurring.
Is there some way to reconfigure HttpWebRequest/Response to NOT throw WebException, and allow the consumer to determine their own error handling? I know that there are some round-about ways of handling Expect-100-Continue with older Http1.0 servers...I'm curious if there is a similar round-about way to disable WebExceptions.
(Oh, and just can't resist...a BIG OL' SHOUT OUT to my WONDERFUL friends over at RedGate for illegally taking away the license-bound FREE version of Reflector 6...I might be able to figure this one out on my own if I could snoop the code...but alas...Reflector is sadly an nonviable option now that it has consumed itself via autolysis. ;P )
I had a similar problem and solved it with the following helper method:
public static HttpWebResponse MakeRequest(HttpWebRequest request)
{
try
{
return (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
if (we.Response != null)
{
return (HttpWebResponse)we.Response;
}
throw;
}
}