C++/winRT coroutine try/catch not working - visual-c++

I have a C++/winRT coroutine that reads a file. The following 'gets' the file:
StorageFile _fileDoubles = co_await _turboCalc.GetFileAsync(L"FileDoubles.dbo");
Which executes properly because the file exists. If I change its name to a nonexistent file, my app fails with this error message:
Exception thrown at 0x76903AC2 in IBuffer.exe: Microsoft C++ exception : winrt::hresult_error at memory location 0x02FBE338.
If I enclose it in the following try/catch, My app still fails and with the same error message.
try {
StorageFile _fileDoubles = co_await_turboCalc.GetFileAsync(L"FileDoublesZZZ.dbo"); //doesn't exist
}
catch (hresult_error const & e) {
printf("error: %ls\n", e.message().c_str());
}
What is the proper way to use try/catch in a couroutine?

Related

Access Denied exception being thrown in UWP

I'm trying to save a video file to a specific folder location instead of a library; which is what it defaults saves to. I'm using StorageFolder.GetFolderFromPathAsync to get the location. When it reaches that line in the function it'll throw the exception. 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
private async Task StartRecordingAsync()
{
try
{
// Create storage file for the capture
var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);
var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
// Calculate rotation angle, taking mirroring into account if necessary
Debug.WriteLine("Starting recording to " + videoFile.Path);
await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
_isRecording = true;
_isPreviewing = true;
Debug.WriteLine("Started recording!");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when starting video recording: " + ex.ToString());
}
}
Code in between
private async Task SetupUiAsync()
{
var lvmptVid = await StorageFolder.GetFolderFromPathAsync("C:\\Users\\Nano\\Documents\\lvmptVid");
// var videosLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
// var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
// Fall back to the local app storage if the Pictures Library is not available
_captureFolder = lvmptVid;
}
I've tried using different saving techniques, currently in the process of revamping the process.
I've tried using a public file location instead of a user specific one.
When you are trying to use GetFolderFromPathAsync to get the file directly using a path, please make sure that you've enabled the broadFileSystemAccess capability in the manifest file.
Like this:
<Package
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap">
<Capabilities>
<rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>
Please also remember to enable the file system settings in Settings > Privacy > File system.
Like this:

Groovy catch block not catching MultipleCompilationErrorsException

I am trying to catch an exception (MultipleCompilationErrorsException) but am having a hard time doing so (actually I am trying to catch all types of errors and exceptions if that matters). Here is what I have tried:
try {
some erroneous crap here
println("wtf! A")
} catch(Throwable all) {
println("caught!")
}
This works. caught! is shown as the output.
try {
try some erroneous crap here
println("wtf! A")
} catch(Throwable all) {
println("caught!")
}
This code errors out with:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: /tmp/g.groovy: 2: expecting '{', found 'some' # line
2, column 9.
try some crap here
^
1 error
So now that I have the exception name, I tried:
try {
try some erroneous crap here
println("wtf! A")
} catch(MultipleCompilationErrorsException e) {
println("caught!")
}
This errors out exactly like the above:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: /tmp/g.groovy: 2: expecting '{', found 'some' # line
2, column 9.
try some crap here
^
1 error
Can someone tell me what I am missing? How does one catch such an error/exception?
"Try Catch's" are generally used to handle exceptions that may pop up during the run time of your code. For example, you can try to run a command that requires a certain plugin/library to be imported but if the user doesn't have the respective plugin/library, then the "catch" will handle this exception.
In your case, it seems that you are trying to handle an actual error with the code syntax within your try block. The try block cannot run at all if the syntax is not correct (this would be the compilation error). My best advice would be to try running what ever is inside your try block first to see if it will throw an exception and then implement a try catch block.

Catch block not called on Groovy exception in NiFi ExecuteScript processor

I'm using NiFi ExecuteScript to call a Groovy script that extracts text from PDFs. When it fails to extract, an Exception is supposed to be thrown and the flowfile is redirected to REL_FAILURE. Some PDFs go through fine, and some give the error:
ExecuteScript[id=9a39e0cb-ebcc-31e4-a169-575e367046e9] Failed to process session due to javax.script.ScriptException: javax.script.ScriptException: java.lang.IllegalStateException: StandardFlowFileRecord[uuid=2d6540f7-b7a2-48c7-8978-6b90bbfb0ff5,claim=StandardContentClaim [resourceClaim=StandardResourceClaim[id=1538596326047-12, container=default, section=12], offset=2134, length=930225],offset=0,name=1 i-9 INS rev 87 05-07-87.pdf,size=930225] already in use for an active callback or an OutputStream created by ProcessSession.write(FlowFile) has not been closed: org.apache.nifi.processor.exception.ProcessException: javax.script.ScriptException: javax.script.ScriptException: java.lang.IllegalStateException: StandardFlowFileRecord[uuid=2d6540f7-b7a2-48c7-8978-6b90bbfb0ff5,claim=StandardContentClaim [resourceClaim=StandardResourceClaim[id=1538596326047-12, container=default, section=12], offset=2134, length=930225],offset=0,name=1 i-9 INS rev 87 05-07-87.pdf,size=930225] already in use for an active callback or an OutputStream created by ProcessSession.write(FlowFile) has not been closed
My (simplified) code is below:
def flowFile = session.get()
if(!flowFile) return
flowFile = session.write(flowFile, { inputStream, outputStream ->
try {
// Load PDF from inputStream and parses text into a JSON string
// If nothing can be extracted, throw an exception so the flowfile
// can be routed to REL_FAILURE and processed further down the NiFi pipeline
if(outputLength < 15) {
throw new Exception('No output, send to REL_FAILURE')
}
// Write the string to the flowFile to be transferred
outputStream.write(json.getBytes(StandardCharsets.UTF_8))
} catch (Exception e){
System.out.println(e.getMessage())
session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)
session.transfer(flowFile, REL_SUCCESS)
It pretty closely follows the cookbook posted in the Hortonworks community forums, and the author even mentions that closing is handled automatically.
I think that the error is caused when a PDF fails to process. This throws an exception, which should be caught in the try{}catch{} and then be transferred to REL_FAILURE. Instead it appears that the catch{} is never getting called, so the outputStream object is never closed. It works as expected and gets caught just fine when I run the same Groovy code outside of NiFi.
If you want to try running it on your own server
NiFi template
full Groovy code.
Sample PDF
The try/catch should be outside the session.write() call rather than in the callback. Inside the callback, throw an IOException rather than an Exception, that should be propagated up through the session.write() and should enter your catch clause outside. Then you can transfer the flow file to failure (you shouldn't be allowed to transfer the flow file while you're writing to it).

Fail early vs. robust methods

I'm constantly (since years) wondering the most senseful way to implement the following (it's kind of paradoxic for me):
Imagine a function:
DoSomethingWith(value)
{
if (value == null) { // Robust: Check parameter(s) first
throw new ArgumentNullException(value);
}
// Some code ...
}
It's called like:
SomeFunction()
{
if (value == null) { // Fail early
InformUser();
return;
}
DoSomethingWith(value);
}
But, to catch the ArgumentNullException, should I do:
SomeFunction()
{
if (value == null) { // Fail early
InformUser();
return;
}
try { // If throwing an Exception, why not *not* check for it (even if you checked already)?
DoSomethingWith(value);
} catch (ArgumentNullException) {
InformUser();
return;
}
}
or just:
SomeFunction()
{
try { // No fail early anymore IMHO, because you could fail before calling DoSomethingWith(value)
DoSomethingWith(value);
} catch (ArgumentNullException) {
InformUser();
return;
}
}
?
This is a very general question and the right solution depends on the specific code and architecture.
Generally regarding error handling
The main focus should be to catch the exception on the level where you can handle it.
Handling the exceptions at the right place makes the code robust, so the exception doesn't make the application fail and the exception can be handled accordingly.
Failing early makes the application robust, because this helps avoiding inconsistent states.
This also means that there should be a more general try catch block at the root of the execution to catch any non fatal application error which couldn't be handled. Which often means that you as a programmer didn't think of this error source. Later you can extend your code to also handle this error. But the execution root shouldn't be the only place where you think of exception handling.
Your example
In your example regarding ArgumentNullException:
Yes, you should fail early. Whenever your method is invoked with an invalid null argument, you should throw this exception.
But you should never catch this exception, cause it should be possible to avoid it. See this post related to the topic: If catching null pointer exception is not a good practice, is catching exception a good one?
If you are working with user input or input from other systems, then you should validate the input. E.g. you can display validation error on the UI after null checking without throwing an exception. It is always a critical part of error handling how to show the issues to users, so define a proper strategy for your application. You should try to avoid throwing exceptions in the expected program execution flow. See this article: https://msdn.microsoft.com/en-us/library/ms173163.aspx
See general thoughts about exception handling below:
Handling exceptions in your method
If an exception is thrown in the DoSomethingWith method and you can handle it and continue the flow of execution without any issue, then of course you should do those.
This is a pseudo code example for retrying a database operation:
void DoSomethingAndRetry(value)
{
try
{
SaveToDatabase(value);
}
catch(DeadlockException ex)
{
//deadlock happened, we are retrying the SQL statement
SaveToDatabase(value);
}
}
Letting the exception bubble up
Let's assume your method is public. If an exception happens which implies that the method failed and you can't continue execution, then the exception should bubble up, so that the calling code can handle it accordingly. It depends one the use-case how the calling code would react on the exception.
Before letting the exception bubble up you may wrap it into another application specific exception as inner exception to add additional context information. You may also process the exception somehow, E.g log it , or leave the logging to the calling code, depending on your logging architecture.
public bool SaveSomething(value)
{
try
{
SaveToFile(value);
}
catch(FileNotFoundException ex)
{
//process exception if needed, E.g. log it
ProcessException(ex);
//you may want to wrap this exception into another one to add context info
throw WrapIntoNewExceptionWithSomeDetails(ex);
}
}
Documenting possible exceptions
In .NET it is also helpful to define which exceptions your method is throwing and reasons why it might throw it. So that the calling code can take this into consideration. See https://msdn.microsoft.com/en-us/library/w1htk11d.aspx
Example:
/// <exception cref="System.Exception">Thrown when something happens..</exception>
DoSomethingWith(value)
{
...
}
Ignoring exceptions
For methods where you are OK with a failing method and don't want to add a try catch block around it all the time, you could create a method with similar signature:
public bool TryDoSomethingWith(value)
{
try
{
DoSomethingWith(value);
return true;
}
catch(Exception ex)
{
//process exception if needed, e.g. log it
ProcessException(ex);
return false;
}
}

How can I get the line number of a SyntaxError thrown by require(id) in node.js?

(source: nocookie.net)
I am trying to get access to the text I highlighted in red inside my nodejs program. I currently have a try/catch block around the require call, but the stack trace I dump in the catch does not contain the information I am trying to access (namely, the line number in 'testdebug.js' where the error occurred).
The lines highlighted in red are printed by something in node's internals, apparently. How can I store that string inside of my program? Code is below.
var syntaxError = true;
try {
debugModule = require('./testdebug.js')
syntaxError = false;
}
catch(e) {
console.log(e.stack);
//there was a syntax error.
}
This guy knows what's up. His module checks the code for parser errors using esprima, and gives a useful object for dissecting them.
https://github.com/substack/node-syntax-error

Resources