Capturing errors in Rust (Rust URL) - url

Please note I'm using a nightly build of Rust 0.13.0
First off, I'm a beginner to Rust and am still in the process of consuming as much information as possible on the language. Throughout my consumption the one topic I've been able to find very little on is error handling. So, when I first attempted to use an external library in my code I became quickly stumped at how I should be using the material being returned to me.
To help explain my confusion, I will be referencing the rust-url library. Here is some sample code found in the documentation:
use url::{Url, InvalidIpv6Address};
assert!(Url::parse("http://[:::1]") == Err(InvalidIpv6Address))
This is pretty straight-forward to me. However, my next question was: what about the other errors? I looked further into the ParseError enum and found 15+ other types of errors that could be potentially produced by a malformed URL.
So, my question is, what is considered the proper way to handle all of these various conditions? Should I have a lengthy match that alerts out specialized messages for each one? Is there a way to consume them all at once?
I apologize if there is not a single answer to this question, but Google was not making it clear and I would prefer to have feedback on this before I proceed coding the rest of my project the wrong way.

The ParseError enum implements the Show trait, with a custom useful message for each variant, so when you get to the final step of actually handling the parse error (e.g. after manipulating the Result in whatever ways you see fit), you can just treat the error possibilities as a black box:
fn download(s: &str) {
match Url::parse(s) {
Ok(url) => { ... }
Err(e) => {
println!("Could not parse '{}'. {}.", s, e);
}
}
}
will print things like Could not parse 'http://[:::1]'. Invalid IPv6 address..
(I filed #43 about making the Show message lower-cased, so that it flows better in more complicated error messages.)

Url::parse returns ParseResult<Url> which is defined as Result<Url, ParseError>, so you can make use of generic Result methods:
use url::{Url, InvalidIpv6Address};
assert!(Url::parse("http://[:::1]").is_err());
Result is Rust's preferred method for error handling, and has many convenience methods under the hood. For example, if you don't expect the failure you can use .unwrap() to make any failure fatal. When they don't suit your needs, you can also match against the Result.

Related

Swift: Is there an OS call in macOS/iOS similar to NSSpellCheck but for getting a word definition from the dictionary,

I can spell check words like this:
import Cocoa
let words = ["happy","flingey","bookinto"]
let spellCheck = NSSpellChecker()
for word in words {
if spellCheck.checkSpelling(of: word, startingAt: 0).length == 0 {
print("Word: \(word) is good")
} else {
print("Word: \(word) is bad")
}
}
However, the output is:
Word: happy is good
Word: flingey is bad
Word: bookinto is good
There are some (only some) combinations of valid words, like "book into" but with a missing space which the spellchecker still accepts as valid.
I suspect I might be able to tweak how NSSpellChecker operates to eliminate the issue, however, if I can get the next part working, I won't need to worry about this one.
For a later part of the App (a quiz) I want to let the user see a definition of the word within the App. Something like this
import Cocoa
let definer = NSDictionaryDefinition()
let word = "Happy"
if let meaning = definer.getDefinition(for: word) {
print("\(word): \(meaning.getText())")
}
Which would then give:
Happy: feeling or showing pleasure or contentment
NSDictionaryDefinition is just something I made up as the kind of API name I was expecting to find, and obviously given how macOS APIs work it won't be as easy as that, it will probably be within a collection within a container within a callback, or whatever, but I'm happy dealing with all that when I get there, my problem is I can't find any system API that remotely resembles something like NSDictionaryDefinition.
My web search is hampered by the fact that Dictionary is also a Swift Collection Type, so I get hundreds of false hits, but even trawling through many of those, I didn't get lucky.
So next I started looking in the API references on the Apple developer site, which is just as painful because it's so vast and sprawling with little by way of a route map through it, but even then I couldn't locate anything.
Does anyone know if this system API exist for Swift (or even Objective-C). I've always assumed it did because the dictionary comes as standard in macOS and most things in macOS are programable via an API. It needs to be a system native API to work offline and also localise to the user automatically.
Please don't suggest third party resources, as I notice a previous question about that got marked as off-topic here. I'm assuming this question is on topic but I genuinely struggle to gauge it.
Thanks.
Something like this exists on iOS. Look into UIReferenceLibraryViewController. It doesn't give you back the definitions as strings, but you can check if there is a definition for a word and you can show the system-provided dictionary view.

Proper way to return error from within a mutateAndGetPayload

I am doing a number of business logic checks within the mutateAndGetPayload function of a relay mutation using the graphql-relay library. For any of these checks that fail I have an else clause that will throw an error, ig throw('You do not have permission to delete this resource');, however, when that happens, I get the error Cannot set property 'clientMutationId' of undefined returned to the frontend instead of the error I'm trying to return. It seems that I'm seeing this error because I'm not returning something this mutation cares about (or a promise that resolves to one), so I'm a little stumped ... what's the proper way to throw/return errors back to the client here?
One way is to use the GraphQLError Type
Working in NodeJS on the back end we have used the following library:
https://github.com/graphql/graphql-js/tree/master/src/error
However, what we have ended up using is a library that provides more flexibility:
https://github.com/kadirahq/graphql-errors
Either of these would be the best place to start.

Can you prevent short-circuit evaluation in Lua?

I am working on a script that allows user entry of Lua (specifically, boolean conditionals), and I am trying to provide a feature that will perform a quick error check for the script that is entered.
It's easy enough to throw an error if loadstring() fails, so syntax issues are readily handled.
However, if variables are improperly entered, it is harder to detect a problem.
Let's say the user enters the following:
value.custom_value_1 == 1 and valse.custom_value_2 ~= 1
As far as the syntax goes, loadstring() is quite satisfied -- it adds 'return ' as a prefix to that string.
My next step is to check for errors when we execute what was entered by the user. The problem is, when value.custom_value_1 ~= 1, the logic will short-circuit since we're dealing with and - there's no point in going further, we already have false on the left-hand side.
What I would like is to find a way to cause Lua to completely evaluate the expression, rather than short-circuiting. If it did so, the spelling error valse would be caught (regardless of value.custom_value_1's value) and I can provide an error message to the end user.
Any thoughts?
My current best idea is to filter through the user input, sorting out every value entered (basically, whatever's not an a conditional or, and, ...) and just doing it manually. But I thought it's worth checking to see if there's a better way.
Preventing short-circuit evaluation is not something you would want to / could do. That's just the way it works.
What you could do instead is something like:
if(logic1 and logic2)
{
// code on success
}
else
// check what kind of error we have
{
if(~logic1)
{
// throw error type 1
}
if(~logic2)
{
// throw error type 2
}
}
If you don't mind parsing the string up-front you could use a library like https://github.com/stravant/LuaMinify/blob/master/ParseLua.lua to parse the source into an AST, modify the short-circuiting notes into function calls like
function my_and(x, y)
return x and y
end
Then you compile this AST to check for the errors.
Seems a lot hassle though just to catch trivial errors.
I'm not sure if anyone's answer was accurate, but the literal question was 'can you prevent short-circuit evals' and I was not able to find a way to do that.
I ultimately chopped up the user input and tested each component individually, gathering those errors and feeding them back to the user. Seems okay for now.

Customizing All errors symfony 1.4

Sorry for my English and writing through a translator.
I'm new here and I'm a bit lost in what I want, maybe you can help me out if they wish, as explained here:
I want to customize all the errors that may be produced (any status code that is a mistake. 404, 500, 204, 301 .... etc.) And also show suggestions based on the "module" and/or "action" from where the error occurred.
I also wish I could tell by the file redirection "setting.yml" application, something like this:
error_404_module: common
error_404_action: errors
error_500_module: common
error_500_action: errors
error_204_module: common
error_204_action: errors
error_301_module: common
error_301_action: errors
........
Within the "app/frontend/modules/common" in the "action.class.php" define "executeErrors" in which I receive the status code that has occurred and the module where the error occurred or except for well, getting partial show "app/frontend/modules/common/templates/_errorXXXSuccess.php" and the partial of the suggestion that I seek and extract the module "referer" where the error occurred.
Well, that's the idea, dynamic content for different types of error in different circumstances and working perfectly with the type codes 404 but not with the rest ...
I read that could place me in the middle of the event by creating a file "config/error.html.php" and "config/exception.html.php". Indeed if I produce such a 500 error and manually these files are executed. The problem is that from there I can not access variables from symfony. Because if so I could invoke "common/errors" and bad send as parameters the error status code and the module where it occurred, but it is not. From there all I can do is play with $ _SERVER and routing.yml but can not get good results because the environment is mixed with Development Production (/frontend_dev.php) and is something I also want to avoid.
That is, I want to get as in "setting.yml" does "error_404_module" and "error_404_action" but with different error codes. Thus allowing me to show my custom pages in production based on "error or exception" and/or "module or action" where the error has been released from production, and in case of being in development mode (/frontend_dev.php/....), show the symfony Dispatch.
Surely life is complicandome and has a simpler way to do what I want but after thousands of combinations do not get the right result. Even if symfony may not allow other types of error redirect from "setting.yml" is because they are reserved for him or something. I do not understand.
Please please help me because no documentation to find and secure here at least we left public for others who want to do something.
Many Thanks and greetings!
First of all - you can't get symfony to intercept all errors. Some of the errors may be server errors and the request won't even get to your application. You can reproduce some of them explicitly setting responses in symfony though, but I may not be necessary to deal with all of them.
As for the exact response: you should use a listener to hook your errors to a class that handles them according to your need. See: https://stackoverflow.com/a/7077818/580167 for implementation details.

Removing ModelErrors from ModelState once written to ValidationSummary()

I may be approaching this from the wrong angle entirely, but hopefully someone will know a way of acheiving what I'm after.
I reference a web service, which returns an ErrorInfo object. I add each returned error to the ModelState as a ModelError:
foreach(ErrorInfo error in serviceResponse)
ModelState.AddModelError(error.AssociatedField, error.Description);
For errors which relate to a particular input field (using strongly-typed Views here), I get a nice inline error returned to Html.ValidationMessageFor(x), which is great.
The problem is that in addition to these input-related errors, there may also be more generate results.
What I'd LIKE to do is have these output in a list similar to Html.ValidationSummary() - however if I do this at the moment, it will also include the errors which have already been displayed inline against each input.
Is there an elegant way of just displaying all the errors which DON'T relate to a particular form input?
This is a good enough solution for me, it doesn't print the individual error detail, but thats not important for the non-input related errors
Html.ValidationSummary(true, "Failed to login for some other reason")

Resources