Mongodb c# InsertOne() - How to Handle exception - mongodb-.net-driver

I am using mongodbc# driver which includes legacy driver. And using InsertOne() method insert records. But it is void, how do I know if there is error in insertion and what type of exception is thrown.

It will raise an exception if an error occurs. http://mongodb.github.io/mongo-csharp-driver/2.2/reference/driver/error_handling/#write-exceptions

Just use Try Catch
try {
db.products.insertOne(
{ "item": "envelopes", "qty": 100, type: "Self-Sealing" },
{ writeConcern: { w : "majority", wtimeout : 100 } }
);
} catch (e) {
print (e);
}
it will catch the Exception.

Related

APP: Error: Got Self Message of unknown kind

I'm using Veins 5.0 framework version. Each node sends a self-message to send its own defined message to other nodes.
However, the following error log is output on the node. The error is output, but the following code seems to run fine.
APP: Error: Got Self Message of unknown kind! Name: mR_TQ Event
The code part of each file is structured as follows.
RSU.h
...
enum ApplMessageKinds
{
SEND_FRTQ_EVT,
SEND_ENTP_EVT,
SEND_ENTC_EVT,
SEND_MRTQ_EVT
};
...
RSU.cc
...
void RSU::initialize(int stage)
{
if(stage == 0)
{
...
frtqMsg = new cMessage("FR_TQ MSG", SEND_FRTQ_EVT);
entpMsg = new cMessage("EN_TP MSG", SEND_ENTP_EVT);
mrtqMsg = new cMessage("mR_TQ MSG", SEND_MRTQ_EVT);
}
else if(stage == 1)
{
if(frtqMsg -> isScheduled()) { cancelEvent(frtqMsg); }
else { scheduleAt(simTime() + 3.0, frtqMsg);
if(entpMsg -> isScheduled()) { cancelEvent(entpMsg); }
else { scheduleAt(simTime() + 2.0, entpMsg);
if(mrtqMsg -> isScheduled()) { cancelEvent(mrtqMsg); }
else { scheduleAt(simTime(), mrtqMsg);
}
}
void RSU::handleSelfMsg(cMessage* msg)
{
DemoBaseApplLayer::handleSelfMsg(msg);
switch(msg -> getKind())
{
case SEND_FRTQ_EVT:
{
...
break;
}
case SEND_ENTP_EVT:
{
...
break;
}
case SEND_MRTQ_EVT:
{
...
break;
}
}
}
Many nodes send and receive messages at the same time, but is this relevant? I think there is no grammatical problem, but I don't understand why the problem occurs.
The mentioned error comes from DemoBaseApplLayer::handleSelfMsg(msg). Involving this method must be done only when in your switch the matched kind is not found, i.e.:
void RSU::handleSelfMsg(cMessage* msg)
{
switch(msg -> getKind())
{
case SEND_FRTQ_EVT:
{
...
break;
}
case SEND_ENTP_EVT:
{
...
break;
}
case SEND_MRTQ_EVT:
{
...
break;
}
default: {
DemoBaseApplLayer::handleSelfMsg(msg);
break;
}
}
}

finally block equivalent for exception handling in CompletableFuture

I have CompletableFuture which can return result or exception. I want to perform run some common code in case of exception and normal result. Similar to try catch finally block
Current implementation
CompletableFuture<Integer> future= CompletableFuture.supplyAsync(this::findAccountNumber)
.thenApply(this::calculateBalance)
.thenApply(this::notifyBalance)
.exceptionally(ex -> {
//My Exception Handling logic
return 0;
});
Where i can put my finally logic ?
The closest equivalent to finally is whenComplete. Like handle, it accepts a function receiving either, a result value or a throwable, but it doesn’t provide a substitution result value, but rather, the new completion stage will not alter the result, just like finally.
So
static int decode(String s) {
try {
return Integer.parseInt(s);
}
finally {
System.out.println("finally action");
}
}
is equivalent to
static int decode1(String s) {
return CompletableFuture.completedFuture(s)
.thenApply(Integer::parseInt)
.whenComplete((myParsedInt, error) -> System.out.println("finally action"))
.join();
}
So when using with
for(String s: Arrays.asList("1234", "foo bar")) try {
System.out.println("decoded: "+decode(s));
} catch(Exception ex) {
System.out.println("decoding "+s+" failed with "+ex);
}
the first variant prints
finally action
decoded: 1234
finally action
decoding foo bar failed with java.lang.NumberFormatException: For input string: "foo bar"
and the latter prints
finally action
decoded: 1234
finally action
decoding foo bar failed with java.util.concurrent.CompletionException: java.lang.NumberFormatException: For input string: "foo bar"
Common to both is that an exception thrown within the finally action will supersede the original result, shadowing the exception, if the try block/ previous stage completed exceptionally.
handle() Method provide more flexible approach. it takes a function receiving either correct result or exception:
From java doc
handle(BiFunction<? super T,Throwable,? extends U> fn)
Returns a new CompletionStage that, when this stage completes either
normally or exceptionally, is executed with this stage's result and
exception as arguments to the supplied function.
CompletableFuture<Integer> thenApply = CompletableFuture.supplyAsync(this::findAccountNumber)
.thenApply(this::calculateBalance)
.thenApply(this::notifyBalance)
.handle((ok, ex) -> {
System.out.println("Code That we want to run in finally ");
if (ok != null) {
System.out.println("No Exception !!");
} else {
System.out.println("Got Exception " + ex.getMessage());
return -1;
}
return ok;
});

How to avoid nesting do/catch statements in Swift2

I keep wanting to do this:
do {
let result = try getAThing()
} catch {
//error
}
do {
let anotherResult = try getAnotherThing(result) //Error - result out of scope
} catch {
//error
}
But seem only to be able to do this:
do {
let result = try getAThing()
do {
let anotherResult = try getAnotherThing(result)
} catch {
//error
}
} catch {
//error
}
Is there a way to keep an immutable result in scope without having to nest do/catch blocks? Is there a way to guard against the error similar to how we use the guard statement as an inverse of if/else blocks?
In Swift 1.2, you can separate the declaration of the constant from the assignment of the constant. (See "Constants are now more powerful and consistent" in the Swift 1.2 Blog Entry.) So, combining that with the Swift 2 error handling, you can do:
let result: ThingType
do {
result = try getAThing()
} catch {
// error handling, e.g. return or throw
}
do {
let anotherResult = try getAnotherThing(result)
} catch {
// different error handling
}
Alternatively, sometimes we don't really need two different do-catch statements and a single catch will handle both potential thrown errors in one block:
do {
let result = try getAThing()
let anotherResult = try getAnotherThing(result)
} catch {
// common error handling here
}
It just depends on what type of handling you need.

How to unit test throwing functions in Swift?

How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType is thrown?
EDIT: Updated the code for Swift 4.1 (still valid with Swift 5.2)
Here's the latest Swift version of Fyodor Volchyok's answer who used XCTAssertThrowsError:
enum MyError: Error {
case someExpectedError
case someUnexpectedError
}
func functionThatThrows() throws {
throw MyError.someExpectedError
}
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.someExpectedError)
}
}
If your Error enum has associated values, you can either have your Error enum conform to Equatable, or use the if case statement:
enum MyError: Error, Equatable {
case someExpectedError
case someUnexpectedError
case associatedValueError(value: Int)
}
func functionThatThrows() throws {
throw MyError.associatedValueError(value: 10)
}
// Equatable pattern: simplest solution if you have a simple associated value that can be tested inside 1 XCTAssertEqual
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.associatedValueError(value: 10))
}
}
// if case pattern: useful if you have one or more associated values more or less complex (struct, classes...)
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
guard case MyError.associatedValueError(let value) = error else {
return XCTFail()
}
XCTAssertEqual(value, 10)
// if you have several values or if they require more complex tests, you can do it here
}
}
At least of Xcode 7.3 (maybe earlier) you could use built-in XCTAssertThrowsError():
XCTAssertThrowsError(try methodThatThrows())
If nothing is thrown during test you'll see something like this:
If you want to check if thrown error is of some concrete type, you could use errorHandler parameter of XCTAssertThrowsError():
enum Error: ErrorType {
case SomeExpectedError
case SomeUnexpectedError
}
func functionThatThrows() throws {
throw Error.SomeExpectedError
}
XCTAssertThrowsError(try functionThatThrows(), "some message") { (error) in
XCTAssertEqual(error as? Error, Error.SomeExpectedError)
}
Given the following functions and declarations:
enum SomeError: ErrorType {
case FifthError
case FirstError
}
func throwingFunction(x: Int) throws {
switch x {
case 1:
throw SomeError.FirstError
case 5:
throw SomeError.FifthError
default:
return
}
}
This function will throw a FifthError if 5 is given to the function and FirstError if 1 is given.
To test, that a function successfully runs the unit test could look as follows:
func testNotError() {
guard let _ = try? throwingFunction(2) else {
XCTFail("Error thrown")
return
}
}
The let _ may also be replaced by any other name, so you can further test the output.
To assert that a function throws, no matter what ErrorType the unit test could look like this:
func testError() {
if let _ = try? throwingFunction(5) {
XCTFail("No error thrown")
return
}
}
If you want to test for a specific ErrorType it's done with a do-catch-statement. This is not the best way compared to other languages.
You have to make sure that you...
return in the catch for the correct ErrorType
XCTFail() and return for all other catch
XCTFail() if no catch is executed
Given this requirements a test case could look like this:
func testFifthError() {
do {
try throwingFunction(5)
} catch SomeError.FifthError {
return
} catch {
XCTFail("Wrong error thrown")
return
}
XCTFail("No error thrown")
}
Swift 4.1 Error throwing Test for associated values
enum ParseError: Error, Equatable {
case unexpectedArgument(String)
}
func testWithNoSchemaButWithOneArgument() {
XCTAssertThrowsError(try Args(withSchema: "", andArguments: ["-x"])) { error in
XCTAssertEqual(error as? ParseError, ParseError.unexpectedArgument("Argument(s) -x unexpected."))
}
}
You can use this function:
func XCTAssertThrowsError<T, E: Error & Equatable>(
_ expression: #autoclosure () throws -> T,
error: E,
in file: StaticString = #file,
line: UInt = #line
) {
var thrownError: Error?
XCTAssertThrowsError(
try expression(),
file: file,
line: line) {
thrownError = $0
}
XCTAssertTrue(
thrownError is E,
"Unexpected error type: \(type(of: thrownError))",
file: file,
line: line
)
XCTAssertEqual(
thrownError as? E,
error,
file: file,
line: line
)
}
Example:
XCTAssertThrowsError(try funcThatThrowsSpecificError(), error: SpecificErrorEnum.someError)

do try catch swift 2

HI i am a little confused about how to transfer if_else error handling to do try catch successfully.
Here is my code.
let error : NSError?
if(managedObjectContext!.save()) {
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
if error != nil {
print(error?.localizedDescription)
}
}
else {
print("abort")
abort()
}
and now i converted to swift 2.0 like this
do {
try managedObjectContext!.save()
}
catch {
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
print((error as NSError).localizedDescription)
}
I am confused about where to print abort and do the abort() function
Any idea~? Thanks a lot
Rewriting your code to work the same as your original code
do {
try managedObjectContext!.save()
//this happens when save did pass
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
//this error variable has nothing to do with save in your original code
if error != nil {
print(error?.localizedDescription)
}
}
catch {
//this happens when save() doesn't pass
abort()
}
what you probably want to write is the following:
do {
try managedObjectContext!.save()
//this happens when save did pass
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let saveError as NSError {
//this happens when save() doesn't pass
print(saveError.localizedDescription)
abort()
}
Everything within do {} is good, everything within catch {} is bad
do {
try managedObjectContext!.save()
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let error as NSError {
print(error.localizedDescription)
abort()
}
use either the error handling or the abort() statement

Resources