Await in async function without try and catch in sails mongo db - node.js

I am using sails JS and mongo db for my web app.
my code is working fine. But i am having a doubt.
my database statements are like this:
var a = await users.create({username:username,id:id}).fetch();
No try and catch. No error handling.
it is working perfectly fine in my local host. If i Moved to production, will that create a problem??

Any promise that has any chance of rejecting MUST have an error handler of some type. If you don't and you hit that error, your JS will essentially crash with an unhandled exception.
It's just bad programming not to handle any possible errors in some way. You should catch the error, log it and return some sort of error status from whatever http request probably initiated this call.
No error handling. it is working perfectly fine in my local host.
Sure, as long as there's NEVER an error with the database call, it works perfectly fine. What would you expect to happen if there was some sort of database error? Do you want your server crashing? Would you know what was causing it if your server just crashed? Would your users get any feedback that there's a problem?
If i Moved to production, will that create a problem??
It certainly could. If something happened with the data for this call or something happened to your database that led to an error, then your server may crash and whatever http request initiated this would never get a response.
It is just poor programming to not handle all possible errors in some way in your server. It's a common shortcut or lack of attention to detail, but it's always a mistake. As a senior developer involved in code reviews for less senior developers, this was a reason to fail the code review and require further attention to proper error handling.

No it will Not cause probleme but if you got error when this procedure is runing how would you know imagine you did that in many several places in your app and there is some ood issue happining how would you know where is coming from ?
so you Need to do that for more error handling!

Related

NodeJS - Is it OK to call db insert/update functions without await?

I have a backend application and there are insert/update endpoints. They mostly go as:
Check and validate the input
Submit the input to db
Return status 200/201 with location header set and body contains status message
Would it be ok to make the 2nd step without await so that response can be returned faster? The returned status will be set to 202, which means it is currently processing. The possibility of 2nd step to throw error is extremely low, or if it does there is a bug going on somewhere and does not relate to the end-user anyways, hence no need to return such error to user.
Would this work? Even if this works, would it be a good practice?
It's OK to not wait for the database response to succeed before doing other things (like sending back a response) if that's how you want your app to work and you're sure that's the right design and you've thought through what happens (from the end user's point of view) if that database call (that you didn't wait for) fails.
BUT, it's not OK to ignore a rejected promise that might come back from the database call because unhandled promise rejections should not happen in a nodejs server. So, if you're not going to use an await, then you probably need a .catch() to catch and at least log the error.
Would this work?
Yes. There's nothing in the language or in nodejs stopping your from sending a response before the database call has completed. It's more about whether that's the appropriate way to design your response handler.
Even if this works, would it be a good practice?
It's not a widely recommended practice because the usual sequence is this:
Check and validate the input
Submit the input to db
If success, return status 200/201 with location header set and body contains status message
If error, return appropriate error status (based on type of error) and status message.
I'm not saying that you can never deviate from this sequence, but doing so would generally be the exception, not the rule.
Keep in mind that data validation does not necessarily catch everything that might cause the database to generate an error. For example, you could be creating a new user on your site and the email address is perfect valid in validation, but then the database rejects it because it's not unique (there's already a user with that email address).
And, the database itself could be having problems, causing an error and the user should be informed that the transaction they were trying to submit to the database did not happen event though the error was not directly caused by the user.

Maximum call stack size exceeded when using Nestjs validation pipeline with form-data (Fastify)

since the owner just closed my issue on GitHub and the people on the official discord server couldn't help me, I'm trying my luck here.
Since NestJS doesn't have interceptors or anything else for fastify (for file uploads), I wanted to use the fastify-multipart (now #fastify/multipart) package. I registered the middleware the normal way, but I'm using the attachFieldsToBody option, so I can properly use the validation pipeline which I've set to global. I have a very simple setup with a DTO for my post request. If you let the sandbox container run, you'll see the 500 error saying maximum call stack exceeded which happened in the validation pipeline.
GitHub Issue: https://github.com/nestjs/nest/issues/9683
Sandbox: https://codesandbox.io/s/nestjs-fastify-multipart-bug-17m5ls
The multipart middleware works fine (even though someone on Discord thought that was an issue, assuming that I didn't google for it). The only issue is the validation pipeline, but I can't track this down, I'm unsure why it causes an infinite loop. While I'm debugging and looking through the common package source code, if anyone ran into this issue or has an idea for a solution, please let me know.

Determine route that causes PayloadTooLargeError

We have a NodeJS app that uses Express. We've seen a few PayloadTooLargeError message start to pop up, but the problem is we don't know whats causing it or how to recreate. The error message also doesn't give us any indication of which route the error is occurring on. Is there a way for the stack trace or error message to detail which route is causing the error? We have quite a few routes with APIs from multiple services, so debugging them all is almost impossible.
Adding a custom middleware that logs the request uri before the route is called will allow you to see which uris are throwing errors.

Node.js: Should I discard request on error?

When I build server using Node.js. Requests can sometimes fail. For example, there can be error in parsing POST data. When any error happens:
should I continue handling the request and risk that some of those POST data may be corrupt or missing and respond as if nothing happened (or respond and notify the user, that some error happened)?
try to reparse POST data (and if it fails for, let's say, 3 times, stop trying, add error to error log and show error page to user)?
stop the request handling immediately and throw 500 error?
What is the best way?
The key questions to ask yourself in this situation are IMO:
do I know why the error happened;
can I recover from it?
The answers depend solely on your application. Generally, retrying something only makes sense if you can expect a different outcome with the next attempt. This typically applies to various unexpected errors when integrating with external systems. On the other hand, if the error that you get clearly states that it received e.g. a bad request, or that a file does not exist, then this is probably not going to change no matter how many times you retry the same operation.
If your business rules allow you to continue the operation while ignoring the error entirely, then do so. If your business rules allow you to carry out the request partially and you're able to report the partial failure - then do so. If the error prevents any processing of the request whatsoever, then you'll have to terminate it and report back to the user.
It seems to me that you had a particular situation in mind, so let me address request body re-parsing. In a proper system doing this should be utterly pointless - if you expect different outcomes, then there is something fundamentally wrong with your setup because the body of a request should not change once it's received. Your application should never modify request data in any way.
As a more general rule - if you expect that something unexpected might happen in your application, but you have no idea when, why or how, then there is something wrong with how the application is structured / executed. You should own your code and know exactly what it does.

How to avoid users getting 500 Errors when server throw exception

I get the following errors in my server log.
2012-03-06 09:20:43 HTTP JVM: CLFAD0211E: Exception thrown. For more detailed information, please consult error-log-0.xml located in D:/Lotus/Domino/data/domino/workspace/logs
2012-03-06 09:20:43 HTTP JVM: CLFAD0229E: Security exception occurred servicing request for: /demo.nsf/home.xsp - HTTP Code: 500. For more detailed information, please consult error-log-0.xml located in D:/Lotus/Domino/data/domino/workspace/logs
The user only sees this in the webbrowser (source)
<html>
<head>
<title>Error</title></head>
<body text="#000000">
<h1>Error 500</h1>HTTP Web Server: Command Not Handled Exception</body>
</html>
So I can tell by the server log that there is a security exception thrown at the server, probably because I have wrong settings in my java.policy file. but my issue is not what is causing the error, but rather how can I avoid users getting these ugly 500 errors.
I would like the error page I have set in the application to be presented to the user just like any other exception.
possible?
The more try/catch blocks you have in your code, the better (within reason, of course):
try {
// code that might throw an error
} catch (e) {
// examine the error to see if there's a workaround
// if not, log it and inform the user
} finally {
// any code that needs to run whether or not there was an error
}
This way if something fails, it fails gracefully. Just be sure to make it obvious to the user that something went wrong (and, preferably, provide them instructions they can actually follow up on)... failing silently is even worse than an ugly error page if something went wrong and the user thinks everything was fine.
P.S. As Stephan indicates, there are some errors that simply can't be caught. If the XPage wasn't signed by someone with access to run XPages, for instance, it never even gets to the point of trying to run your code... the page itself is invalid, so there's nothing you can do at runtime. Always make sure that your XPages are signed during deployment.
There are a number of errors that "break through" even if you have an error page defined. E.g. when you drag a control onto itself. Security seems another area. All of them are stuff you should handle in development. I haven't seen errors that "typically" happen (true runtime after development completed and tested type of errors) escaping a custom error page. Other than that follow Declan's advice.
I had an issue like this also where my error page was not being displayed and the error 500 page would display instead.
What I discovered is that there was a problem in my error page also and the renderer therefore can't display the error for the original page and you get the server default error page instead.
The best way to check if this is the cause of your particular issue is to start with a simple error page, no theme, no ssjs libraries, no ssjs code on the page etc, just a blank xpage with some static text to indicate that it is the error page.
Once you can confirm that this is the possible cause of the error 500 then you can start building up that error page and add in the dynamic stuff bit by bit till it is the way you need it.
Dmytro Pastovenskyi has a good article http://dpastov.blogspot.com/2012/01/error-pages-in-domino.html about error pages in Domino.
To be on the safe side I have a static html page saying "An error occured". This page is referenced by the HTTPMultiErrorPage setting in the notes.ini on your server.
Then there is a "HTTP response headers" rule addressing special error codes.
The main problem still is, that these are global settings. So there is no easy way to catch all errors specially for your application. But a least the user don't get this annoying white error page.
I have had similar issues with this. Error messages bubbling up from some underlying fault that overrides the defined error page for the application. This is not a nice behavior (from a user perspective) and makes you feel a bit naked. I do understand that it's hard for the application to trap those - but there should at least be a way to customize that message - The default error 500 page is not very useful for a normal user anyway...
The only(?) way to try to avoid that your code throws such error (ssjs/java) is to (as Tim Tripcony already mentioned) always use try/catch statements around the code (as you already know :))
getDocumentByUNID() is a "good" example of a method that will cause the ugly (but standard) error 500 page to be displayed instead of the defined one in the app.
As for any other error types (system/security and such) - I don't think it's possible to redirect those to the (by the user) invoked applications error page because they are not invoked from the application but rather before the application is invoked (I hope I'm wrong).
Make a new XPage called error.xsp (for example). Put there some basic info that something went wrong, apologize for that fact and provide few links how to continue with the work (even though his/her data may be lost forever - history.go(-1) usually does not resolve the problem). In the background you can log the error (usage of OpenLog recommended).
Open Application Properties, XPages tab. Uncheck Display XPages runtime error page. In the combo Error page select your page (error).

Resources