How to treat global errors without displaying the error ribbon in spartacus - spartacus-storefront

I am doing the following call to execute an action only in case an user exists
private _userConnector: UserConnector,
....
this._userConnector.get(userId).subscribe(() => {
// conditional action
},
(error) => {
console.log('your handling goes here');
});
However, if the userId does not exist the error ribbon appears on the back:
I dived deep in all the method calls behind _userConnector.get but I did not find how to only catch the error in susbscribe avoiding the red error ribbon.

Error handling is implemented in low level http interceptors. There's a documentation that describes the handlers and how to customise them.
The error that you notice in the message box is likely driven by the ForbiddenHandler, which is configured to handle 403 errors. You can customise the handler to avoid the error in the message box. See the implementation on github.

Related

Vuex how to handle api error notification?

I started working with Vuex 2 weeks ago and I realized that Vuex is very good to handle the state of the app. But, it is difficult to handle the error of API calls. When I get data from the server, I dispatch an action. When data is successfully returned, of course, everything is fine. But when an error happens, I change state, I don't know how to detect it through the state from Vuejs components to notify to the user. Could anyone give me some advice?
I typically have the following parts:
A component for displaying the notification, typically an alert or a snackbar or similar, e.g. error-notification. I use this component on a high level, directly below the root app component. This depends on your layout.
A property in vuex indicating the error state, typically an error object w/ error code & message, e.g. error
One mutation in the store for raising an error setting the error property, e.g. raiseError
One mutation in the store for dismissing an error clearing the error property, e.g. dismissError
Using these, you need to:
Display error-notification based on the error in the store: <error-notification v-if="$store.state.error :error="$store.state.error"/>
When an error occurs, call raiseError mutation (in your API callback): vm.$store.commit('raiseError', { code: 'ERR_FOO', msg: 'A foo error ocurred'})
In error-notification, call the dismissError mutation when the notification is closed.
You can also return a promise in your action so that if you call it from component you can catch the error there and display a notification as needed:
in your store:
//action
const fetch = (context) => {
return api.fetchTodos() //api here returns a promise. You can also do new Promise(...)
.then((response) => {
context.commit('SET_TODOS', response);
})
};
in vue component:
this.$store.dispatch('todos/fetch', modifiedTodo)
.catch(error => {
//show notification
})

Redux—global error handler

I am running redux on node. To handle asynchronous actions, like reading a file or listing of a directory, I am using redux-thunk in combination with Promises. So a typical action can look like that:
const
fs = require('fs'),
{ promisify } = require('util'),
readdir = promisify(fs.readdir);
const listFiles = dir => dispatch =>
readdir(dir)
.then(files => dispatch({
type: '…',
payload: { files }
}));
So:
try {
store.dispatch(listFiles('/some/path'));
catch (error) {
//some rescue plan here,
//won't work if directory not exists
}
wont work here, because the action is asynchronous and right now, the only way I see to handle all errors is to add a .catch() to all promises in all actions and dispatch an error action there.
That has two downsides:
a lot of code repetition and
i need to know all possible errors in ahead.
So my question is: Is there any way to create a global error handler, which will also be called if an asynchronous action fails, such that I can add some error indicating information to the state, which can be displayed?
Could that be possible with a »storeEnhancer« or some »middleware«?
UPDATE
I could find something that is really helpful:
process.on('unhandledRejection', (reason, promise) => {
console.log(reason.message);
});
That callback is triggered whenever a Promise is rejected and no catch block is added. Right now that seams to do the trick, but anyway, I would prefer a solution that basically does the exact same thing, but only for rejected Promises which are triggered within store.dispatch(), so only when an error within the processing of actions/middleware/reducers within redux comes to happen.
If you're looking for a redux middleware solution, take a look at redux-catch.

How to return error from Auth0 hooks

If I want to return custom error from Rules I simply do callback(new UnauthorizedError('Custom error message here')) but how do I do the same thing with Hooks?
callback('error message');
callback(new Error('error message'));
Those didn't worked and "UnauthorizedError" is undefined in Hooks. Whatever I do, on front-end side I always get "WE'RE SORRY, SOMETHING WENT WRONG WHEN ATTEMPTING TO SIGN UP." and when I inspect result of requested I see that there is no difference, each time "InternalExtensibilityError" comes.
Why do I want to return error from Hooks? I run extra validation for sign-up there.
Now it is possible to send custom error messages in hooks.
I extracted below code snippet from Auth0's documentation on hooks.
module.exports = function (user, context, cb) {
const isUserDenied = ...; // determine if a user should be allowed to register
if (isUserDenied) {
const LOCALIZED_MESSAGES = {
en: 'You are not allowed to register.',
es: 'No tienes permitido registrarte.'
};
const localizedMessage = LOCALIZED_MESSAGES[context.renderLanguage] || LOCALIZED_MESSAGES['en'];
return cb(new PreUserRegistrationError('Denied user registration in Pre-User Registration Hook', localizedMessage));
}
};
Here is the original link (https://auth0.com/docs/hooks/extensibility-points/pre-user-registration)
At the moment, returning custom errors from hooks to the top-level API, /dbconnections/signup in this case is not possible in Auth0. This is documented in the bottom of this page.
Note that Hooks is still in Beta, and this enhancement request is one of the most asked for features and it is currently in our backlog. We cannot give an ETA for this yet. You can submit your feedback to the Product here.

How to handle back button after returning a promise from the activate callback in Durandal

We are developing a mobile application using Durandal 2.1
The documentation states that we can return a promise from the activate callback and it should cancel navigation on failure.
We've been trying to use that feature, but it breaks the back button in our application.
As you can see in Durandal's router.js plugin code, the cancelNavigation function is navigating towards the lastUrl:
function cancelNavigation(instance, instruction) {
system.log('Navigation Cancelled');
router.activeInstruction(currentInstruction);
router.navigate(lastUrl, false);
isProcessing(false);
rootRouter.explicitNavigation = false;
rootRouter.navigatingBack = false;
router.trigger('router:navigation:cancelled', instance, instruction, router);
}
Because of that behavior, using the back button after navigation cancellation will not provide the expected results since it will navigate back to the page that caused the error.
Are we using this feature in the wrong way?
Our goal is to try to load data in the activate function, and then navigate back to the current page if an error occurs.
Any help regarding this woule be greatly appreciated.

Express handling CSRF error

How can I implement a custom error handler in Express using CSRF middleware after users click the back button in browser and resubmit the form? By default Express return a 403 page with lots of stack traces. I want to replace it by for example redirecting user to a custom error page. How can I do that?
Here are some examples of writing custom error handlers in Express: https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js
Here are the custom error handlers I use: Error handling in an Express route
You might also want to consider modifying connect to return a different code than 403 when CSRF fails. You can change it here: https://github.com/senchalabs/connect/blob/master/lib/middleware/csrf.js#L82
You might choose 428 Precondition Required. The full list is here: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
That way, you could have a special message shown only for CSRF failures.
Like any other well designed middleware csurf passes the error to next. So it's possible to react on the raised error in the following way:
var csurf = require('csurf')();
app.use(function (req, res, next) {
csurf(req, res, function (err) {
if (err) {
// do what ever with err
} else {
next();
}
});
});