Nancy RequiresClaims failure returns a 403. How do I use this? - nancy

If a module requires a claim, and the user does not have the claim a 403 response is returned.
eg:
this.RequiresClaims(new[] { "SuperSecure" });
or
this.RequiresValidatedClaims(c => c.Contains("SuperSecure"));
but that just returns a blank page to the user.
How do I deal with a user not having the required claim?
Can I 'catch' the 403 and redirect?
The RequiresClaims method returns void or uses the pre-request hook to throw back a HttpStatusCode.Forbidden. What should I do so the user knows what has happened?
Many Thanks,
Neil

You can catch it either by writing your own post request hook (either at the app level, or the module level) or by implementing your own IErrorHandler, probably wrapping the default one.
The error handler stuff is going to change so you will be able to register multiple ones (for different error codes), it's setup to do that (with the "can/do" interface) but for some reason my brain didn't add it as a collection :-)

Related

Cypress: Try/Catch block for External Services?

So what I want to do might be impossible and actually may not even be recommended, but im curious of the best way to handle this.
Currently one of my applications attempts to use an external service (Specifically google maps API). Sometimes I get a bad response from googles API (or it times out). It's rare (less than 1/30 times maybe) but it still happens and introduces flakiness into the automation tests.
I thought about stubbing this out everytime, but that would also sort of I feel like "lower" the test value (Since google maps api is important in this case)
I was curious if Cypress is able to do something that would TRY to get a response (with a successful status code) and if it failed maybe leave a log note but allow the test to continue on (either via stubbing or just continuing on).
This may even be a bad idea as we don't really "know" from just looking at the results but I wanted to at least pose the question.
Thanks!
You could achieve this by only conditionally sending mocked data, based on the response to that API call.
cy.intercept('/foo', (req) => { // replace with the URL for the google API
req.continue((res) => { // pass through the request to the real API
if (res.statusCode !== 200) { // or whatever "success" statusCode/criteria is
cy.log('my information I want to log')
res.send(200, myMockedBody) // send the mocked response.
}
res.send(); // otherwise, just send the response from the API
});
});

Error: There was a problem getting the Conversation associated with this room

I'm trying to implement this project: https://github.com/twilio/twilio-video-app-react
I got error "There was a problem getting the Conversation associated with this room." when the ChatProvider did mount. Seem like chatClient can't find the conversation with room.sid but I can't figure out how to create conversation when it doesn't exist and add participants when conversation existed. Does anyone know this issue? Thanks!
Update: the server code: https://gist.github.com/qngnud/c9910afada625a9a4eceb3ad3a67d3b7
Twilio developer evangelist here.
It appears that you are using similar code to the original app in your server, however you have missed a crucial keyword.
The part of the code where you try to fetch a conversation by the room.sid is surrounded by a try/catch, however it is called in promise form, so any failures will be picked up by a chained .catch() function.
In the original code, the calls are made using the await keyword which turns promises into code that appears synchronous and, most importantly, in which errors can be caught by a try/catch block.
So, you should either move your catch blocks to .catch() promise chains, or declare the whole function async and use await before the asynchronous function calls.
I fixed this issue by adding member in the channel before joining the twilio room.
To add member in the channel, I used the api provided by twilio => Click here.
After adding the member in the channel, ChatClient will find the conversation with roomSid.
And I used chatClient.getConversationBySid('CHXXXXXXXXXXXXXXXXXXXXXX') instead chatClient.getConversationByUniqueName(room.sid).
Happy Coding!

Best practices for displaying and managing error messages in React-Redux app

I am building a React app (with react-redux, redux-saga, and axios), and
I need advice on how to arrange my project for displaying user-friendly error messages.
(It is up to me to decide what and how I display to the user)
In particular, I would like to get answers to the following questions:
Should I display a message based on the status code?
Should I break down the errors to client / server / other errors and what are the benefits of that? (based on example from Axios)
Where should I keep the error messages, in the component itself, in a config file (I would like to see an example of such a file)?
How would my redux state tree look?
Should I dispatch an action for every error based on the status code?
I would appreciate any suggestions or real-world examples.
Here are some examples of error responses from our backend:
Request URL: https://example.com/api/call/123
Request Method: POST
Status Code: 400 Bad Request
Request URL: https://example.com/api/call/123
Request Method: PUT
Status Code: 409 Conflict
Request URL: https://example.com/api/user/me/
Request Method: GET
Status Code: 401 Unauthorized
It basically depends on what method you are trying to display the message, For instance, in our own projects, We are using a global snack bar component to display errors if any have occurred during the requests.
Most of the time users don't care about the status code, if you want not to be very specific then you can display a simple alert/snack bar for example: "Sorry, Some error occurred".
If you are sure that you do need to show specific errors to the user the I definitely recommend a constant file for errors which will store all your error message, You can keep them in constants directory in the store folder so maybe even in /helpers, It depends on your choice.
Yep, you can definitely divide your errors based on if the error was on the server or the client-side.
I don't think the redux tree will change if you're not managing errors in the tree. If you want to, definitely use a snack bar/alert reducer on the top of the tree
You may not want to show the same error for a status code in each of different components, Otherwise, if you want to, You can use it but that would add a lot of unnecessary code into your requests.
For our projects, since we are using i18 for internationalization, We have a snack bar reducer and the action folder, We import the snack bar actions in our sagas and just display a simple error message ( You definitely can customize it for your needs accordingly), That's all,Keep it simple.
yield put(Actions.apiRequest);
try {
const res = yield axios.put('/todo/', updateData);
if (res.data.status === 'success') {
yield put(Actions.fetchTodos(todoID));
yield put(snackbarSuccess('Todo Saved Successfully !'));
} else {
throw new Error();
}
} catch (error) {
yield put(Actions.apiError);
yield put(snackbarError(REQUEST_FAIL)); // an imported constant
}
Some basic code behind my implementation.
1) Assuming you're also doing the BE or can ask someone to adjust the response - It might be best to return a body with your API error response, and avoid just HTTP status codes - if possible. That could then contain an error 'code' that maps to a message on your front-end, as well as field name which can be really helpful for displaying errors in the right place on forms, etc. alternatively, the entire message could come from the BE and the FE simply display it. I work on an enterprise-level codebase that uses both these methods.
2) Regarding error message, i'd always store them in a common file but beyond that up to you really. It sort of depends on how you implement #1. Personally I like error 'codes' stored in an enum file, which correspond to a message because you can then do other logic from that (e.g. don't display the rest of a form if error X is triggered, use a custom message for the error code in one situation or fall back to a default
3) Not sure - I guess you'd do that if you want to log server-side errors but show client. Where I work we differentiate purely for different logging categories I think.
4) Again depends on your implementation - somewhat up to you. Some form packages will handle this for you in redux. Others will just use local state and not redux for this.
5) Would make sense to, yes. Again if you look a custom error code returned in the body of the API call that'll give you more flexibility.
I hope that gives you some ideas, based on my experience rather than any set way of thinking.
have a look at https://reactjs.org/docs/error-boundaries.html as well, and if you haven't already REST APIS / best practice for REST API: https://blog.restcase.com/rest-api-error-codes-101/

Checking for presence of an item without using expect

In my web application, the Sign Out link is only shown once the user has logged in - it's not present on the login page.
In my Protractor tests, I want to make sure the user is logged in - which means that in my first test, I have to log in. To check whether the user is logged in or needs to log in, I want to check for the presence of the Sign Out link.
I don't want to do this using expect, since not having the Sign Out link present on the page is perfectly acceptable, it just means that I have to log in.
What I'm looking for is a way to implement an if scenario in my test (in a beforeEach function) - pseudo code:
if (!signOut.isPresent()) {
login();
}
So far, I haven't found an easy way to do this - all of the checks for presence of an item in the page's DOM seem to rely on expect, which throws an exception when the item is not present on the page.
Is there an easy way to do that?
You may just catch the exception.
Or use findElements and check if the returned list of elements is empty, which means the element is not present.
(Not sure about the second solution cause I don't know Protractor, but findElements is what you would use in Java)
The answer by #alb-i986 got me on the right track. After looking at the findElement API, I found two references on how to do the error handling for a this function:
https://github.com/angular/protractor/blob/master/docs/api.md#webdriverwebelement
https://github.com/angular/protractor/issues/485#issuecomment-33951648
Protractor is returning a promise from the findElement function, and the promise's then function (which is called once the promise is resolved) takes two callback arguments:
The first one is called when the promise is resolved successfully, i.e. the element was found on the page.
The second one is optional. When it's not provided, the standard error handling takes place in case the element was not found. This means that the No Such Element exception is thrown. When providing the callback, it's your own responsibility to handle the error there. The error object is provided as a parameter to that callback.
Making use of the second (optional) callback, you can decide to handle or ignore the error:
protractor.getInstance().findElement(by.css(".signout-button"))
.then(function(element) {
// The element was found on the page - click it.
element.click();
}, function(error) {
// Sign out button is not present - handle the error or ignore it
});

What's is the right way to trigger an error callback in Backbone if my response has a certain flag?

This is my use case: I call fetch on a collection and receive a JSON from my server yet I have an error flag. This will always trigger the success flow, and I can detect the error by 2 means:
In my parse method - which is ugly.
By not using the success option, and using the Deferred's Done callback to check for the error. This is ugly as well since I have to call parse myself afterwards.
This would be solveable if Backbone had a validate function on collection but it doesn't...
Any suggestions?
EDIT: I know there's a way to do it by supplying my own Sync method but I got a bit lost there...
good question.. I'm not sure it's so bad to work with the parse method. It's name doesn't fit but it's all you've got in the natural path of the code and I guess you can just return an empty list without breaking anything.
The question to me is what is the cause of the error? If it's, say, a permissions thing (or some other error covered by the http protocol), you could return an error code from the server which should trigger your error callback..

Resources