Bug with mine 'AutoImport' function - c#

There is my error in console:
2022-01-17T08:43:15.669Z] Executed 'AutoImport' (Failed,
Id=cfafc70c-40f4-4b42-9af5-76ca76daa53d, Duration=652ms)
[2022-01-17T08:43:15.670Z] System.Private.CoreLib: Exception while
executing function: AutoImport. TeamsAllocationManager.Integrations:
An unexpected error occurred calling external API.
service:FutureDatabase; code:NotFound; message (optional):Not Found.
And there is a code of function:
[FunctionName("AutoImport")]
public async Task AutoImport([TimerTrigger("*/15 * * * * *")] TimerInfo timer, ILogger logger)
{
using (logger.BeginScope(new Dictionary<string, object>
{
["AppVersion"] = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "-",
["Action"] = "AutoImport",
}))
{
try
{
logger.LogInformation($"Auto Import action started");
var command = new ImportProjectsAndEmployeesCommand();
await _dispatcher.DispatchAsync<ImportProjectsAndEmployeesCommand, ImportReportDto>(command);
}
catch (Exception ex)
{
LogException(logger, ex);
throw;
}
}
}
Error triggers in handler by line:
ICollection<User>? users = await _futureDatabaseApiClient.GetUsersAsync();
Im not sure why it occurs, it happen only in dev, in azure i didnt noticed this error. I had a clue about nugets but idk how to figure out which package is missing ( i tried install few or update some and error still occurs).
Sombody know the solution?

The FutureDatabaseApiClient you're using is calling an API that doesn't exist. The error message clearly states:
An unexpected error occurred calling external API. service:FutureDatabase; code:NotFound.
This might be because of a (base) URL not set correctly, or it being a relative URL.

Related

Custom Error Messages and Exception Handling in Bot Framework Composer

I am trying to have Custom Error messages for any any Exceptions thrown by Bot Framework Composer Bot. As the custom runtime of Composer project does not have bot.cs file, it is not possible to implement OnturnError. I have tried to add it in Startup.cs but it is not working. Is there a way I can implement this ?
I have also tried adding a Error handling class inheriting from cloudAdapter and adding it as a service in Startup.cs.
public class AdapterWithErrorHandler : CloudAdapter
{
public AdapterWithErrorHandler(BotFrameworkAuthentication auth, ILogger<IBotFrameworkHttpAdapter> logger, ConversationState conversationState = default)
: base(auth, logger)
{
OnTurnError = async (turnContext, exception) =>
{
// Log any leaked exception from the application.
logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");
// Send a message to the user
var errorMessageText = "The bot encountered an error or bug.";
var errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput);
await turnContext.SendActivityAsync(errorMessage);
errorMessageText = "To continue to run this bot, please fix the bot source code.";
errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput);
await turnContext.SendActivityAsync(errorMessage);
if (conversationState != null)
{
try
{
// Delete the conversationState for the current conversation to prevent the
// bot from getting stuck in a error-loop caused by being in a bad state.
// ConversationState should be thought of as similar to "cookie-state" in a Web pages.
await conversationState.DeleteAsync(turnContext);
}
catch (Exception e)
{
logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}");
}
}
// Send a trace activity, which will be displayed in the Bot Framework Emulator
await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
};
}
}
Startup .cs
services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();
You can use "Error occurred event" to handle errors and custom error messages, steps on how to handle exceptions in BotComposer

Catch exception in xunit test

Can I catch the exception that appears in the log but not in the test?
I performed the test and it returned the status: OK, but in the log I have:
Unexpected error publishing create package to Kafka. id = 5ec3eb81aa662c8a7c76e5e8. Exception: System.NullReferenceException: Object reference not set to an instance of an object.
How can I catch this exception in the test? I tried to use Try and catch (Exception) but nothing catches.
[Fact]
[DisplayTestMethodName]
public async Task ExceptionTest()
{
try
{
var testRequest= #"{""Test1"":"1234"};
var testRequestResp =
await fixture.PostAsync(testRequest);
Assert.Equal("HttpStatusCode: " + System.Net.HttpStatusCode.OK, "HttpStatusCode: " + testRequestResp.StatusCode);
}
catch (Exception ex)
{
Assert.True(ex == null, "Exception: " + ex.Message);
}
Log
VS log
This means you are handling the NullReferenceException already somewhere in your PostAsync method and still returning status 200. That is a design decision to swallow the error and return "OK" (hopefully you are logging it or something at least).
A different approach would be to return a 500 status instead of 200, to indicate that an internal server error has occurred - then try and address the NullReferenceException.
You may also choose not to swallow the error in you PostAsync method and let it bubble all the way up. In that case, you could use:
var exception = await Assert.ThrowsAsync<NullReferenceException>(() => fixture.PostAsync(testRequest));
(Where testRequest was something you knew would trigger that error)
If getting a NullReferenceException is expected behavior and the request is still "OK" status, then somehow catching it in your test would make no sense.
I want to check that the exception "NullReferenceException" does not occur.
I used your advice:
var exception = await Assert.ThrowsAsync<NullReferenceException>(() => fixture.PostAsync(testRequest));
But I don't catch this exception
Where is the problem?

Kestrel server crashes on exception

I am using a Kestrel based server application with ASP.net core 2.1. I have a custom error handling middleware like this:
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
Log.Warning(exception,"Exception occurred: {exception}",exception);
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
It seems to work in 99% of the cases, but every now, and then the server process stops, and I see some exception as last logged entry. Unfortunately, I haven't been able to reproduce this on my development machine, it only appears on the production system. In my understanding this should not happen in any case.
Are there any known errors I could make to make the server stop? Is there anything I could enable for diagnostics?
The stacktraces of the logged exceptions usually indicate some issue with the input or things which I would like to report using the ErrorHandlingMiddleware.
Are you using Windows or Liunx? If using Windows you should be able to capture a crash dump on process crash using WER (Windows Error Reporting) https://michaelscodingspot.com/how-to-create-use-and-debug-net-application-crash-dumps-in-2019/#Automatically-create-dump-on-Crash.
On Linux you can do this https://www.cyberciti.biz/tips/linux-core-dumps.html
That should let you collect a crash dump and you can analyze it to see where the crash is coming from.
Generally we catch all exceptions that happen during requests. Crashing the process usually means:
An exception thrown from:
an async void method in your code
A background thread
A stackoverflow exception

Error handling using delegates

I have a common method that I'm using to handle a specific error that may come back from a number of functions:
protected async Task<T> RunMyMethod<T>(Func<T> method)
{
try
{
var returnValue = await Task.Run<T>(method);
return returnValue;
}
catch (MyCustomException)
{
// Force a clean shutdown of the software
ShutdownApplication();
return default(T);
}
}
Here's an example of how that is then used in a derived class:
private async Task<IEnumerable<MyData>> GetMyData()
{
var returnValue = await base.RunMyMethod<IEnumerable<MyData>>(() =>
{
var returnval = GetMyDataFromServer();
return returnval;
});
return returnValue;
}
When an exception of type MyCustomException occurs in GetMyDataFromServer() the software doesn't drop into the catch block. I get the following error in the function GetMyData():
An exception of type 'System.ServiceModel.FaultException`1' occurred in mscorlib.dll but was not handled in user code
Additional information: Exception of type 'MyCustomException' was thrown.
This is with only User-unhandled exceptions turned on.
GetMyDataFromServer() communicates with a WCF service. This service is what throws the error.
ChannelFactory<TChannel> cf = new ChannelFactory<TChannel>(endPointName);
Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
var clientCredentials = new ClientCredentials();
. . .
channel = cf.CreateChannel();
var data = channel.CallWCFService();
Having looked around on-line, it appeared that the correct way to handle this was to change the base method as follows:
protected async Task<T> RunMyMethod<T>(Func<T> method)
{
var returnValue = await Task.Run<T>(method).ContinueWith(e =>
{
ShutdownApplication();
return default(T);
}, TaskContinuationOptions.OnlyOnFaulted);
return returnValue;
}
When I run this, I'm obviously not trapping for the correct error message, but I'm just getting a TaskCancellationException.
So, I have two questions: is my conclusion about how to handle this exception correct and, if so, how do I trap a specific error; and why am I getting a TaskCancellationException?
You get TaskCancellationException because the continuation is cancelled as it's conditional (i.e. TaskContinuationOptions.OnlyOnFaulted) and the condition isn't met since the antecedent task wasn't faulted.
There's no reason to use that method of adding a continuation. Using async-await like you did at the start is good enough (and even simpler).
The issue is that you are trying to catch MyCustomException but that isn't the exception being thrown. Since you're using WCF the exception is FaultException. You can check the "real" exception stored in FaultException.InnerException.

Unable to catch Webservice call method within try catch block

I am developing a WP8 application. I created a web service on out-systems and then I am calling those web service methods in my app:
ServiceReference1.WebServiceClient ws = new WebServiceClient();
try
{
ws.FetchInboxAsync(EmailId);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
Now if the server is down, I expect the control to go into the catch block but it does not and I get the following exception:
An exception of type 'System.ServiceModel.CommunicationException'
occurred in System.ServiceModel.ni.dll but was not handled in user
code.
I do realize that the web service call method is asynchronous, so its exception would not be caught in try catch. On forums, people suggest using await keyword. But when I write
await ws.FetchInboxAsync(EmailId);
I get an error : Cannot await void.
I tried something mentioned in answers here, but still I get the same exception
You can subscribe to FetchInboxCompleted event:
ServiceReference1.WebServiceClient ws = new WebServiceClient();
ws.FetchInboxCompleted += new EventHandler<ServiceReference1.FetchInboxCompletedEventArgs>(c_FetchInboxCompleted);
ws.FetchInboxAsync(EmailId);
And in event handler, check the result:
static void c_FetchInboxCompleted(object sender, serviceReference1.FetchInboxCompletedEventArgs e)
{
// check e.Error which contains the exception, if any
}
If the auto-generated WCF client proxy supports it, you should be able to await a method ending with TaskAsync:
await ws.FetchInboxTaskAsync(EmailId);
If the auto-generated WCF client proxy doesn't define this method, then you can define it yourself as described on MSDN:
public static Task FetchInboxTaskAsync(this ServiceReference1.WebServiceClient client, string emailId)
{
return Task.Factory.FromAsync(client.BeginFetchInbox, client.EndFetchInbox, emailId, null);
}

Categories

Resources