Why the syntax error throw by redeclare a variable using let in io.js can not be catched - io.js

This problem is weird io.js 1.0.4
var assert = require('assert');
assert.throws(function(){
let foo = 'foo';
let foo = 'foo';
},SyntaxError
) // test doesn't pass
assert.throws(function(){
throw new SyntaxError('error')
},SyntaxError
) // test pass

SyntaxErrors are thrown at parse time, before the function has run at all, e.g.
console.log('something something');
function fn(){
let x = 4;
let x = 5;
}
This will throw. Note that not only does console.log not print anything, but fn isn't even being run. So in your case, you can't catch, because the code hasn't even started executing yet.
Note, since parse time is key here, you can catch this kind of thing when the file is being required.
entry.js
try {
require('./module-file')
} catch (e){
if (e instanceof SyntaxError){
console.log('There was a syntax error');
}
}
module-file.js
"use strict";
function fn(){
let x = 4;
let x = 5;
}

Related

Argument passed to call that takes no arguments.. Firebase

Not sure why i'm getting this.. any suggestions would be grateful!
I ran into issues with my original coding where I had Firebase pod and Firebase Package.. so I started from scratch since that wasnt fixing itself.. now I get this.. and I am at a loss for how to resolve it.
static func fetchUsers() -> AnyPublisher<[UserProfile], Error> {
Future< [UserProfile], Error > { promise in
self.db.collection("Users")
.getDocuments { (snapshot, error) in
if let error = error {
promise(.failure(error))
return
}
guard let snapshot = snapshot else {
promise(.failure(FirebaseError.badSnapshot))
return
}
var users = [UserProfile]()
snapshot.documents.forEach { document in
print(users.count)
if let user = try? document.data(as: UserProfile.self){
if users.contains(where: { $0.id == user.id}) {return}
users.append(user)
} else {
print("Not working")
}
}
promise(.success(users))
}
}
.eraseToAnyPublisher()
}
I believe this is the syntax you're after:
var users = [UserProfile]()
users = snapshot.documents.compactMap { (document) -> UserProfile? in
if users.contains(where: { $0.id == user.id}) {
return nil
} else {
return try? document.data(as: UserProfile.self)
}
}
Also be aware that when you iterate something in Swift and encounter a false condition on an iteration, return will return out of the greater scope, not just that iteration. Therefore, use continue.
for x in y {
guard x > 0 else {
continue // continues loop
}
// ...
}

AudioKit exportAsynchronously fails after changing input device

I need to make an ability to change input device for record on the fly while program is running (between recording sessions, not in recording process).
Here is the code that, i suppose, have to do that. But when im trying to change input device, AKNodeRecorder records nothing (duration always 0) and after trying to call exportAsynchronously on recorder.audioFile i always get an following error:
[central] 54: ERROR: >avae> AVAudioFile.mm:37: AVAudioFileImpl: error 2003334207
Tried to change almost all, but nothing has an effect. Here is the code that changes input device.
func setupRecordingChain(_ deviceIndex: Int = 0)
{
AudioKit.stop()
setupInputDevice(for: deviceIndex)
self.micMixer = AKMixer(self.mic)
self.micBooster = AKBooster(self.micMixer)
self.micBooster.gain = 0
do {
self.recorder = try AKNodeRecorder(node: self.micMixer)
}
catch {
//catch error
}
self.mainMixer = AKMixer(self.micBooster)
AudioKit.output = self.mainMixer
AudioKit.start()
}
private func setupInputDevice(for deviceIndex: Int)
{
guard let inputDevices = AudioKit.inputDevices else { return }
let inputDevice = inputDevices[deviceIndex]
do {
try self.mic.setDevice(inputDevice)
} catch {
//catch error
}
}

Debugging Jasmine Custom Matcher Messages

I have the following code for a Jasmine Custom Matcher, as described here:
jasmine.addMatchers({
testingFunction: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
if (expected === undefined) {
expected = '';
}
var result = {};
result.pass = util.equals(actual.myValue, 1, customEqualityTesters);
if (result.pass) {
result.message = "Passed";
} else {
result.message = "Failed";
}
return result;
}
}
}
});
And calling it as such:
.then(function() {
expect({
myValue: 1
}).testingFunction();
})
During debugging, I see that execution goes to my custom matcher but for some reason, neither my Pass or Fail messages get printed to the console.
Any ideas as to why this might be?
Thanks
For anyone else that may be running into this issue, I figured out that in my jasmineNodeOpts, I was overriding the jasmine print method as such:
// Overrides jasmine's print method to report dot syntax for custom reports
//print: () => {},
Removing that fixed my issue.

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.

Code that has run smoothly for days suddenly not working. Not sure how to fix the exception that is being thrown

I have a piece of code that has been running smoothly since I created it, that has suddenly begun to crash every time I run my app. I keep getting EXC_BREAKPOINT that highlights a line in my Thread 1 that states: Swift._getImplicitlyUnwrappedOptionalValue. I've tried adding breakpoints to catch the suspect code within my method, but nothing turns up and I just keep getting this error. I've been at this for a while now, and I'm pretty stumped as to what is going on and how I'm supposed to fix it. Any help is appreciated! Below I've included a screenshot of the error as well as the method I'm trying to call that produces the error. Thanks!
#IBAction func nextPhoto(sender: UISwipeGestureRecognizer)
{
self.deleteResponseMessage(self)
if photoObjects.count == 0
{
var image:UIImage = UIImage(contentsOfFile: "launchImageTall")
feedView.image = image
}
else
{
userInfo.hidden = false
var content:PFObject = photoObjects[0] as PFObject
var recipients = content["recipients"] as NSMutableArray
var userImageFile = content["imageFile"] as PFFile
userImageFile.getDataInBackgroundWithBlock { (imageData:NSData!, error:NSError!) -> Void in
if error == nil
{
var contentImage = UIImage(data: imageData)
self.feedView.image = contentImage
}
}
var profilePicImageFile = content["senderProfilePic"] as PFFile
profilePicImageFile.getDataInBackgroundWithBlock({ (imageData:NSData!, error:NSError!) -> Void in
if error == nil
{
var picture = UIImage(data: imageData)
self.senderProfilePic.image = picture
}
})
var username = content["senderUsername"] as NSString
senderUsername.text = username
var photoCaption = content["photoCaption"] as NSString
senderMessage.text = photoCaption
senderObjectId = content["senderObjectId"] as NSString
for var i=0;i<photoObjects.count-1;i++
{
photoObjects[i] = photoObjects[i+1]
}
if recipients.count == 1
{
content.deleteInBackground()
}
else
{
recipients.removeObject(currentUserObjectId!)
content.setObject(recipients, forKey: "recipients")
content.saveInBackground()
}
}
}
Did you update Xcode recently. Apple is busy updating their cocoa libraries. Every return value was explicitly being unwrapped (like return String!). Now they are going through every function and evaluating whether it should return an instance (return String) or an optional (String?).
So check your code for optionals and remove those ! or ?.
At least that was the case for me with every Xcode update.

Resources