Exception handling in Meteor - javascript

Our product is going to live soon, and some of the users are testing on it. Sometimes, they got the exception randomly and currently, the only way for me to know about it is ssh to the server and scan thousand lines of log in order to know the exception.
In my 8 hours working stack (Java, Spring, ...), I can configure the exception through Aspect, Interceptor in order to watch the exception and notify about the exception through email (sending log file, exception reason to me).
How can I do that in Meteor ? What is the error handling strategy ? Is there any thing that close to Interceptor/Aspect in Meteor so I can inject the email sending during the exception ? I don't really want to use any external service to watch our app for the performance / exception

Some packages look promising. Winston with the email transport kinda suit my needs. I will update this answer if I come up successfully with that

You can configure Email alerts for exception handling.
Add package called email using meteor add email
use callback method
Meteor.call('methodname', function (err, data) {
if (!err) {
//perform some action
}
} else {
console.log(err);
Meteor.call('sendEmail',"error in this method");
//here sendEmail methods send email about the error
}
});

Related

Error "The URI 'XY' is not valid because it is not based on 'XY'" in LogicApp call from JS

I never had an eror like this so I am hoping someboday has a hint regarding this.
I call an HTTP triggered Azure Logic App with javascript by using the XrmQuery.SendRequest() method like this:
XrmQuery.sendRequest("POST", url, JSON.stringify(queryPayload),
function (result) {
showAlertDialog("blabla");
},
function (error) {
console.log("Error", error);
showAlertDialog("blablabla" + error);
});
This script is executed within an Dynamics 365 environment.
the url of the logic app is as follows:
https://xxx.germanywestcentral.logic.azure.com:443/workflows/00000000006942109e13ce0e9c1c4112/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=wzedGSO9vs5pfcDQ9WP0qdc5UBGTU2b-kqbWO8x051E
The error I get is the following:
Error: {"error":{"code":"0x8006088a","message":"The URI
'https://ORGANIZATION_XY.crm4.dynamics.com/aaaa/workflows/00000000000000000013ce0e9c1c4112/triggers/manual/paths/invoke?api-version=2016-10-01&sp=/triggers/manual/run&sv=1.0&sig=wzedGSO9vs5pfcDQ9WP0qdc5UBGTU2b-kqbWO8x051E'
is not valid because it is not based on
'https://ORGANIZATION_XY.crm4.dynamics.com/api/data/v8.0/'."}}
When I call the LogicApp via Postman it works fine. As soon I execute the js code which calls the logic app within Dynamics I get this error.
Anybody knows what this error means?
Any help is highly appreciated.
In simple words "0x8006088a" error code means bad request. It says that the request isn’t correct, because there is an error in query syntax. That’s what you should focus on. There might be some issue with the query string or even the version of the API.
Also note that the Dynamics 365 connector is deprecated but not removed yet. Do not use the Dynamics 365 connector for new logic apps, For connections to Dynamics 365, use the Common Data Service connector.

Mongodb Error codes and corresponding http status code

So, if a new user tries to sign up with an user account that already exists, MongoDb responds with a 11000 error code
In Express, that can be handled like this:
async function signup(req, res, next){
try{
// some stuff
}catch(err){
if (err.code === 11000) {
err.message = 'Email is already taken.';
res.statusCode = 409;
}
return next(err);
}
}
For this example, I decided to respond with a 409 http status code.
However, I am not sure if it's a good approach to handle several different codes from MongoDB and assigning an http status for each of them.
What other solutions am I missing?
You can return specific responses to common errors that you might come across.
But it really comes down to how specific you want to be. You also need to consider is it really worth it to customize the response for each and every single error that can occur. Some of them might never happen depending on your configuration.
For example, ncompatibleShardingConfigVersion will never happen if you are not using a sharded cluster.
Furthermore, if the error message is supposed to be displayed at the frontend, the users don't really care about the what, why, and how of an error. What he/she knows is that it doesn't work and he/she is not happy.
You have several options:
Using conditionals like what you are doing now. Perhaps create a custom error constructor and put the conditionals in it to avoid having to repeat yourself in every single function call.
Send a generic error message to the frontend with status code 500. Log the whole error object at the backend so you can know what went wrong. You are the person who actually cares about the why, what, how, when of an error.
Personally, I will go with option 2.

How to properly handle AJAX errors in ASP.NET Core MVC?

Background:
I'm setting up error handling in an ASP.NET Core 2.2 MVC app. When in development environment, I use the app.UseDeveloperExceptionPage();, and in production - app.UseExceptionHandler("/Error/Index");. I am navigated to the correct error page during non-AJAX (regular form submission) requests based on the environment.
If an exception occurs in the server during an AJAX request, I want the app to display the correct error page depending on the environment.
I have already set up all of what I described above, as you can see in my code examples below.
Problem/Concern:
While this works (though still have to complete the TODO in InitializeGlobalAjaxEventHandlers function), I have some concerns.
With non-AJAX calls in MVC, it feels like there is a "official/correct" way to do it with app.UseDeveloperExceptionPage(); and app.UseExceptionHandler("/Error/Index");, which automatically redirects the program to the error page. With the AJAX end of error handling, however, I don't feel as confident because I pieced it together with parts from different solutions I've researched. I'm worried I'm not aware of what could go wrong.
Question:
Is this the proper way to handle errors during AJAX requests in MVC? Could something possibly go wrong with this set up? Is this in any way improper or too far from common standards?
Code:
Startup.cs > Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//using build config to use the correct error page: https://stackoverflow.com/a/62177235/12300287
//Reason why we don't use environmental variables is because we can't guarantee access to clients'
//machines to create them.
#if (DEVELOPMENT || STAGING)
app.UseDeveloperExceptionPage();
#else
app.UseExceptionHandler("/Error/Index");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
#endif
app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=UserAccess}/{action=Index}/{id?}");
});
}
ErrorController.cs:
public class ErrorController : Controller
{
[AllowAnonymous]
public IActionResult Index()
{
IExceptionHandlerPathFeature exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
Exception exception = exceptionDetails?.Error; // Here will be the exception details.
Error model = new Error();
model.ID = exception.HResult;
model.Message = exception.Message;
model.Path = exceptionDetails.Path;
return View(model);
}
}
Global AJAX error event handler (the if statement is to handle authentication):
function InitializeGlobalAjaxEventHandlers() {
$(document).ajaxError(function (event, xhr, ajaxSettings, thrownError) {
//status is set in the [AuthorizeAjax] action filter if user isn't authenticated
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.redirectUrl;
}
//the document HTML is replaces by responseText value, which contains the HTML of error page
document.write(xhr.responseText);
//TODO: will need to display an error page if responseText is empty, which
//can happen if an AJAX request doesn't reach the server (for example: if URL is incorrect).
});
}
As you explain, there are two threads of code to consider. One is at the client and the other at the server.
Whilst the server can return codes and messages for non-expected results, the client must still be robust and stand-alone. For example, if the server cannot be reached, a time-out error can occur at the client which it must handle. As mentioned above, you can catch errors at the local and global Ajax level.
The server may also generate an error response that never reaches the client.
In some projects I have performed the following:-
If a non-expected result is generated on the server, it is logged in a database and returns an JSON message as an error.
If a non-expected result is generated on the client, a server service is called to log the error on the database.
In both cases, a message is displayed in the current page. A user can also navigate to an error page where recent errors (stored in the database) are displayed.
Working on many project of varying sizes, I've come to the conclusion that there isn't really a solution that fits everything
Is this the proper way to handle errors during AJAX requests in MVC? Could something possibly go wrong with this set up? Is this in any way improper or too far from common standards?
As far as I know, there are no unified/official way of handling Ajax errors in ASP.NET Core MVC project.
Normally we show specific confirm message/content through Ajax error callback function if the Ajax request fails rather than directly displaying detailed exception information to client user, which would help achieve a better customer experience.
If you have specific requirement that requires displaying the Developer Exception Page/custom error page while Ajax request fails, as you did, you can dynamically write the returned responseText to the HTML document using document.write(xhr.responseText); in global error handler.

Handeling Node, Express background errors

I am quite unsure how I should properly handle uncaught exceptions that occurs in my node.js/express app. Right now I have an Express app that will send all caught errors to an Express error handeler using next(err):
function(err, req, res, next) {
// Do something with the error
}
This seems to work all fine and well for errors I have anticipated. For instance a database connection not working, essentially all things that will return a callback(err). Thought problem occurs when I want to preform a background task, which will finish after the response has been sent. For instance:
app.get('/url', function(req, res) {
BackgroundTask.run() // Here an uncaught exception occurs, for instance a bug
res.send('Running your background task')
}
The background modules that I want to run aren't express related (no use of req,res) and upon a caught errors they will use a custom in errorHandeler that will send the error to some error reporting service. However when an uncaught exception occurs in one of these background tasks I have no clue how to send the error to my error report service (Raygun in this case). The only thing that seems to work is to add a process.on('uncaughtException') event listener. However almost every post on the subject describes the latter a 'bad' or crude way of doing things. They seems to recommand using node domains however I don't really see how I can implement these for background tasks.
I use process.on(uncaughtException), because all you're really trying to do is catch the output from the error and shut the server down gracefully (and then restart). I don't see any reason to do anything more complicated than that, because by nature of the exception, you don't want your application doing anything else in that state other than shutting down.
Domains are an alternative way of dealing with this, but it's not necessarily better than using the process handler, because you're effectively writing custom logic to handle things that you aren't anticipating. It does give you finer granularity in terms of what your error handler does for different error types, but ultimately you're still potentially running your application in an unknown state after handling it. I'd rather have my application log the exception, shut down, and then i'll fix the error so it never happens again, rather than risking my user's data on a domain solution which may or may not have handled the error correctly, depending on the nuance of the error it encountered.

Can't get the handshake error message in the client

I'm new to node.js and socket.io (latest versions).
I can't find any good enough documentation about handshaking with socket.io 1.0. I know modules exists, but for the sake of understanding socket.io and node.js, I don't want to add other third party modules (like express).
My code work if I accept the handshake, but if I do as said in the socket.io documentation for the error handling, I don't know how to handle that client side. With the developers tools from Chrome, I can see the error in the Network panel from the server to the client, but I can't figure how to get this value in said client and act accordingly.
Here the piece of code that give me headaches :
io.use(function(socket, next) {
// some checks
if (true) {
next(); // this work
} else {
next(new Error('Authentication error'));
}
}
Maybe I should remove this next(new Error('...')) and just disconnect the socket server side, return something else ?
Or maybe I need to add a parameter somewhere (I also want to stay in websocket mode, not polling) server or client side ?
Thanks !
Ok, just found what I'm missing, I just need to add socket.on('error', function ()); client side to catch the error.

Categories