Cannot handle exception in firebase function - kotlin

i'm trying to understand with no luck why this throwable is not catched in my catch block:
CoroutineScope(IO).launch {
try { FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (task.isSuccessful) {
token = task.result
}
throw Exception("Hi There!")
}).await()
getUsers().await()
}catch (e: Exception){
binding.txtTitle.text = "Error: ${e.message}"
}
}
The exception is called but the app crash and not handle by the catch block. But if i throw an exception outside the addOnCompleteListener the exception is handled normally. My objective is to stop the execution of the getUsers function if no token is available.

The exception which is thrown in OnCompleteListener will not propagate to the outer scope, it is scoped to OnCompleteListener block. To achieve your objective I would recommend to rewrite the code to something like the following:
coroutineScope.launch {
try {
val token: String = FirebaseMessaging.getInstance().token.await()
if (token.isNotEmpty) {
getUsers().await()
}
} catch (e: Exception){
// ...
}
}
await function waits for task to complete.

Related

Why does SignalR recommend using finally to propagate errors in streams?

The SignalR docs on streaming state:
Wrap logic in a try ... catch statement. Complete the Channel in a finally block. If you want to flow an error, capture it inside the catch block and write it in the finally block.
They then proceed to give an example that goes through these convolutions for no apparent gain. Why is this? What difference does it make whether one captures an exception and completes the channel from the finally block versus completing then and there in the catch block?
Possibly to centralize the writer completion logic, even if takes just a single invocation - and you may want to insert additional related logic there (such as logging), if needed.
Exception localException = null;
try
{
// ...
}
catch (Exception ex)
{
localException = ex;
}
finally
{
writer.Complete(localException);
}
versus:
var completed = false;
try
{
// ...
}
catch (Exception ex)
{
writer.Complete(ex);
completed = true;
}
finally
{
if (!completed)
{
writer.Complete(null);
}
}

How to verify exception thrown using StepVerifier in project reactor

def expectError() {
StepVerifier.create(readDB())
.expectError(RuntimeException.class)
.verify();
}
private Mono<String> readDB() {
// try {
return Mono.just(externalService.get())
.onErrorResume(throwable -> Mono.error(throwable));
// } catch (Exception e) {
// return Mono.error(e);
// }
}
unable to make it work if externalService.get throws Exception instead of return Mono.error. Is is always recommended to transform to Mono/Flow using try catch or is there any better way to verify such thrown exception?
Most of the time, if the user-provided code that throws an exception is provided as a lambda, exceptions can be translated to onError. But here you're directly throwing in the main thread, so that cannot happen

What exception type does C++ see when a C# class marked ComVisible throws an exception?

I have a C# class marked ComVisible that has a function that writes to a file. If the folder the file is supposed to be written to does not exist, it throws a System.IO.DirectoryNotFoundException. If I use throw; to raise it back to the C++ client, it doesn't get caught by any handler I know of except a generic (...) one. What is the type of the exception object that the handler will get?
Here is the client method:
void CRXReport::Export(CCOMString Destination)
{
CWaitCursor Wait;
// m_Report->Export("c:/misc/report2.pdf");
CCOMString message;
message << _T("Trying to export a report to ") << Destination;
AfxMessageBox(message);
if ( m_Report != NULL )
{
try
{
m_Report->Export(Destination.AllocSysString());
}
catch (CException& ex)
{
AfxMessageBox(_T("Failed to export the report; caught a CException reference."));
}
catch (CException* pEx)
{
AfxMessageBox(_T("Failed to export the report; caught a CException pointer."));
}
catch (_com_error* e)
{
AfxMessageBox(_T("Failed to export the report; caught a _com_error reference."));
}
catch (...)
{
AfxMessageBox(_T("Failed to export the report; caught something else."));
}
}
}
And, although I don't think it matters, here's the server method:
public void Export(string destination)
{
LogOnToTables();
try
{
_report.ExportToDisk(ExportFormatType.PortableDocFormat, destination);
}
catch (Exception ex)
{
MessageBox.Show("Failed to export report: " + ex.Message);
throw;
}
}
The first comment contains the answer. I needed to catch a _com_error reference, not a pointer.

Handle error for request future calls in volley

I am making synchronous api calls using RequestFuture provided by Volley library.
I need to handle error response when in case the status code is 4xx/500.
try {
JSONObject response = future.get();
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
}
Now the error is caught by ExecutionException catch clause. How do I get NetworkResponse from this error.
How to override onErrorListener in the catch clause.
Try this for grabbing the error from volley. Also just a note when preforming future requests you should use get with a timeout so your not waiting forever.
try
{
JSONObject response = future.get(30,TimeUnit.SECONDS);
}
catch(InterruptedException | ExecutionException ex)
{
//check to see if the throwable in an instance of the volley error
if(ex.getCause() instanceof VolleyError)
{
//grab the volley error from the throwable and cast it back
VolleyError volleyError = (VolleyError)ex.getCause();
//now just grab the network response like normal
NetworkResponse networkResponse = volleyError.networkResponse;
}
}
catch(TimeoutException te)
{
Log.e(TAG,"Timeout occurred when waiting for response");
}

How to write Unit test for Action that throw HttpException with StatusCode 404

I have a below action in a controller which throw HttpException with status code 404:
public async Task<ActionResult> Edit(int id)
{
Project proj = await _service.GetProjectById(id);
if( proj == null)
{
throw new HttpException(404, "Project not found.");
}
}
To test this scenario, I have written below test case where I am catching AggregationException and rethrowing InnerException which is expected as HttpException:
[TestMethod]
[ExpectedException(typeof(HttpException),"Project not found.")]
public void Edit_Project_Load_InCorrect_Value()
{
Task<ActionResult> task = _projectController.Edit(3);
try
{
ViewResult result = task.Result as ViewResult;
Assert.AreEqual("NotFound", result.ViewName, "Incorrect Page title");
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
}
This test run succefully and return ExpectedException. I have two questions here:
Is this right approach for writing unit test or there is more
gracious way of testing it.
Is this possible to check in Unit Test
that user is getting correct error page( NotFound in this case).
There is a nicer way to test this. We wrote a class called AssertHelpers.cs that has this method in it. The reason this is nicer than ExpectedException is that ExpectedException does not actually verify it was thrown, it just allows the test to pass when it is thrown.
For example, if you change your 404 code to return 200 your test will not fail.
public static void RaisesException<TException>(Action dataFunction, string exceptionIdentifier = null)
{
bool threwException = false;
try
{
dataFunction();
}
catch (Exception e)
{
threwException = true;
Assert.IsInstanceOfType(e, typeof(TException));
if (exceptionIdentifier != null)
Assert.AreEqual(exceptionIdentifier, e.Message);
}
if (!threwException)
Assert.Fail("Expected action to raise exception with message: " + exceptionIdentifier);
}