Xamarin forms local store exception when insert item - xamarin.forms

Almost everything works great except one form that doesn't save some data to Azure database and I can't catch any info about exception i.e exception instance is null when break point stop in exception of type MobileServiceLocalStoreException. I checked the initialization of the local store and there is no problem with it, so what could be the reason behind this exception.
public async Task<T> CreateItemAsync(T item)
{
try
{
await table.InsertAsync(item);
}
catch(MobileServiceLocalStoreException ex)
{ // here exception occurd
Debug.WriteLine(ex.Message);
}
catch(Exception ex)
{
}
return item;
}

Related

Configure Windows Service to restart on both graceful AND ungraceful shutdown

I am aware of the Recovery section of the Service control, and how we can set an app to restart after failure.
I have created a .NET 6 worker service to run as a windows service. The problem is that whenever there is an exception in the code, the app logs the error but then shuts down gracefully. This does not signal to windows that the service should be restarted since it returns an exit code of 0.
I've tried returning an exit code of -1 (by setting Environment.ExitCode and returning -1 from Main()) but it's ignored.
I've also tried setting the exit code of the underlying WindowsServiceLifetime and that also does not work.
Are there any ways to have the SCM restart the service no matter how it shut down?
Exceptions should not bring down the host. Exceptions do not bring down IIS and they should not bring down a Windows Service.
You should put try/catch where work begins – every endpoint and background service. In the catch you should log the error.
Here is an endpoint example:
[Route("Get")]
[HttpGet]
public async Task<IActionResult> GetAsync()
{
try
{
return Ok(await BusinessRules.GetSomethingAsync());
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
throw;
}
}
Here is a background service example:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
//Need a try/catch round Task.Delay because exception will the thrown
//if stoppingToken is activated and we don't care about logging this exception.
try
{
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
catch { }
await BusinessRules.DoSomethingAsync(stoppingToken);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
//In a loop, log file can fill up quickly unless we slow it down after error.
try
{
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
catch { }
}
}
}

How to make a method transactional in micronaut

I am using micronaut with sqlite db in my appliation and service class method looks like this:-
private void loadListIntoDb(Stream<EmpDto> lines) {
try {
empRepository.deleteAll();
lines.forEach(empRepository::saveEmpList);
} catch (Exception ex) {
throw new RuntimeException("error while loading file into db", ex);
}
}
What I want is if saveEmpList get failed, all the deleted data by deleteAll method should also get reverted back.
I have tried like this to test but it didn't rolled back the deleted items:
#Transactional
private void loadListIntoDb(Stream<EmpDto> lines) {
try {
empRepository.deleteAll();
throw new Exception("test exception");
} catch (Exception ex) {
throw new RuntimeException("error while loading file into db", ex);
}
}
Is there anything that I am missing.
Regards,
Finally resolved it. We can't make a private method transactional in Micronaut. We need to make the method as public.

How to handle Internal server error (500) on spring rest API to custom the message?

I am working on spring rest api and I would like to sure everything is working fine. I would like to log abnormal behaviors database connection error among others, I'm working with couchbase database and I'm getting in the endpoint response for example for this kind of exception: CouchbaseQueryExecutionException the next message: Unable to execute query due to the following n1ql errors: \n{\"msg\":\"No index available on keyspace kids_club that matches your query. Use CREATE INDEX or CREATE PRIMARY INDEX to create an index, or check that your expected index is online.\",\"code\":4000} and a very long trace.
For this i found a solution on internet that is extend ResponseEntityExceptionHandler and override handleExceptionInternal method like this:
#ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
private static String DEFAULT_VALIDATION_ERROR_CODE = "KC-0020";
#ExceptionHandler(MiddlewareException.class)
protected ResponseEntity<ResponseBody> handleKidsClubException(MiddlewareException ex) {
return buildErrorResponse(HttpStatus.valueOf(ex.getHttpStatus()), ex.toError());
}
#ExceptionHandler(ServiceUnavailableException.class)
protected ResponseEntity<ResponseBody> handleServiceUnavailable(ServiceUnavailableException ex) {
return buildErrorResponse(INTERNAL_SERVER_ERROR, ex);
}
#ExceptionHandler(NoSuchElementException.class)
protected ResponseEntity<ResponseBody> handleNoFoundElement(NoSuchElementException ex) {
return buildErrorResponse(NOT_FOUND, ex);
}
#ExceptionHandler(CouchbaseQueryExecutionException.class)
protected ResponseEntity<ResponseBody> handleCouchbaseQueryException(ConstraintViolationException ex) {
return buildErrorResponse(BAD_REQUEST, ex);
}
}
But I'm not able to catch any kind of Internal Server Error in this way.
It seems like spring is handle and building the final message to the user.
Any ideas to resolve this?
Thanks.
#ExceptionHandler(NullPointerException.class)
public final ResponseEntity<Object> handleNullPointerException(NullPointerException ex, WebRequest request) {
LOGGER.info("Entering into the handleAllException method");
System.out.println("Exception is : " + ex.getClass());
ResponseData error = new ResponseData();
error.setRespCode(HttpStatus.NOT_FOUND.toString());
error.setRespMessage(ex.getLocalizedMessage());
error.setTimestamp(LocalDateTime.now());
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
please try this way below to check whether you are able to catch exception or not.. From the sysout you will get the exact exception. Then you can use that exception to catch any particular exception from that business logic..

Rebus - Exit application from Handle method

I'm implementing an enricher pattern (https://www.enterpriseintegrationpatterns.com/patterns/messaging/DataEnricher.html) using a command/consumer queue where the consumer is the enricher and publishes the enriched message to a separate endpoint (SQL database in this case). The consumer is running as a HostedService which implements cancellation token.
Because I'm consuming commands from one transport and publishing events to another there is a possibility that the transport I'm publishing to is down while the one I'm consuming from is up. In that case I'd like to log an error and stop my Hosted service. However, I cannot see how that would work since whatever calls the Handle method already handles exceptions, and I cannot access my cancellation token. Does anyone have any ideas?
This is a draft of what I want to do.
public async Task Handle(EditedEventData message)
{
var enricher = _enricherFactory.GetEnricher(message);
object #event = await enricher.EnrichAsync(message);
var transformers = _transformerFactory.GetTransformers(message);
var messages = new List<object>();
foreach (var transformer in transformers)
{
messages.AddRange(transformer.Transform(#event, message));
}
foreach (var item in messages)
{
try
{
await _bus.Publish(item);
}
catch (Exception ex)
{
_logger.LogCritical("Publishing event message {#item} failed with error {ex}", item, ex);
//how do I exit from here?
}
}
}
If I were you, I would come up with some kind of application service, e.g. IApplicationControlService, which you can configure to be injected into your handlers using whichever IoC container you're using.
It could look somewhat like this:
public interface IApplicationControlService
{
void RequestApplicationShutdown();
}
and then your code could simply
public class YourHandler : IHandleMessages<EditedEventData>
{
readonly IApplicationControlService applicationControlService;
public YourHandler(IApplicationControlService applicationControlService)
{
this.applicationControlService = applicationControlService;
}
public async Task Handle(EditedEventData message)
{
// (...)
foreach (var item in messages)
{
try
{
await _bus.Publish(item);
}
catch (Exception ex)
{
_logger.LogCritical("Publishing event message {#item} failed with error {ex}", item, ex);
applicationControlService.RequestApplicationShutdown();
}
}
}
}
to request the application be stopped, when an error occurs.
An implementation of IApplicationControlService could then be something like
public class BruteForceApplicationControlService : IApplicationControlService
{
public void RequestApplicationShutdown()
{
Environment.FailFast("you should probably not do THIS 😉");
}
}
or something more gentle 😁 – the point is, that you will be able to provide a way to request your application to shut down "from the outside", most likely from the place where your application is assembled (i.e. the "composition root")

Try-Catch error handiling in ASP.NET

I have one doubt regarding Try-Catch block.
Below is my code
private void PopulateDDL()
{
try
{
if (my condition)
{
code
}
else
{
throw new Exception(ErrorMessage);
}
}
catch (Exception ex)
{
logerror(ex);
}
}
Which Catch block will be executed if error for below code
else
{
throw new Exception(ErrorMessage);
}
From MSDN:
When an exception is thrown, the common language runtime (CLR) looks
for the catch statement that handles this exception. If the currently
executing method does not contain such a catch block, the CLR looks at
the method that called the current method, and so on up the call
stack. If no catch block is found, then the CLR displays an unhandled
exception message to the user and stops execution of the program.
The catch block you have defined:
catch (Exception ex)
{
RaiseWebError(ex);
}
will be executed first for the exception throw new Exception(ErrorMessage);
If RaiseWebError re-throws the exception this will then be handled by the next try-catch block found futher up the call stack (i.e. the parent method you refer to). But if RaiseWebError handles the exception in some way (perhaps by logging the exception) execution will continue after the first try-catch.

Resources