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

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.

Related

Cannot handle exception in firebase function

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.

how to catch sql exception in breeze js

I have a problem in HotTowel template. how can I catch sql duplicate unique key value exception in breeze js and display that?
my controller:
[BreezeController]
[System.Web.Http.Authorize]
public partial class DataServiceController : ApiController
{
[System.Web.Http.HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
SaveResult result;
try
{
result = this._contextProvider.SaveChanges(saveBundle, null);
}
catch (Exception ex)
{
throw ex;
}
return result;
}
}
When the database returns that error, it's hard to match it up to the entity that caused the problem becase MSSQL doesn't tell you much. One can do something like this:
catch (Exception ex)
{
// if a "duplicate key" exception, extract the table name
var match = Regex.Match(ex.Message, "duplicate key.* object '([^']*)'");
if (match.Success)
{
var table = match.Groups[1].Value; // dbo.Customer
var entityType = table.Split('.').Last(); // Customer
throw new HttpException(409, "Duplicate key saving entity " + entityType, ex);
}
throw ex;
}
So that you get a 409 Conflict response code and the type of the entity that caused the problem.

How to get the method name and line number in Exception in ASP Core 5

I want to get the method name and line number when an error occur, I am using Core 5.
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex, "Method Name / Line Number");
}
Update:
I found a Solution like this:
_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());
A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The output would be somewhat like:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
where Main() is the method name and 20 is the line number.
To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}
Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

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

SQL Exception handling Error

In my try catch :-
catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
There is an error in dataprocess..It is underline..I got this code from internet and is there any library to import to re corrct this
You shouldn't really copy code from the Internet and chop it in to your program hoping it will work, unless you understand it.
Try changing dataprocess to the name of the class this code is in.
For example:
public class MyClass {
public MyClass() {
try {
// Do sql stuff
} catch (SQLException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}