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.
Related
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..
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;
}
I have written a windows service which in turn calls a web service. When I run the windows service from a test app., it works perfectly. However when I install the service and then start it, it stops almost immediately. The only two entries I see in the log are Constructor and Thread Started. Not sure what is wrong.
public partial class WindowsService : ServiceBase
{
public LogManager.LogFile _log;
public Thread m_thread;
protected TimeSpan m_delay;
CommonFunctions _cf = new CommonFunctions();
DBFunctions _db = new DBFunctions();
public WindowsService()
{
InitializeComponent();
_log = new LogManager.LogFile(#"c:\test\servicelog.txt", true, true);
_log.WriteToLog("Constructor", LogLevel.Level0);
}
protected override void OnStart(string[] args)
{
m_delay = new TimeSpan(0,0,300);
base.OnStart(args);
try
{
m_thread = new System.Threading.Thread(Execute);
m_thread.Start();
_log.WriteToLog("Thread Started", LogLevel.Level0);
}
catch (Exception ex)
{ _log.WriteToLog(ex.Message, LogLevel.Level0); }
}
public void Execute()
{
_log.WriteToLog("Begin Execute...", LogLevel.Level0);
try
{
ProcessNewLMSUsers();
}
catch (Exception ex)
{
_log.WriteToLog(ex.Message.ToString());
}
}
private void ProcessNewLMSUsers()
{
try
{
_log.WriteToLog("Begin: Processing new LMS Users", LogLevel.Level1);
// Check for new users in the LMS.
string callErrorText = "";
bool userAdded = false;
LMSWS.SSO lms = _cf.GetLMSSSOWS(); **// this is a web service**
lms.Timeout = 99999;
}
REST OF THE CODE.................
}
I can't see there is anything wrong with your code. but you can try to put a "Thread.Sleep(20000); " code at the begining of OnStart method. e.g.
protected override void OnStart(string[] args)
{
Thread.Sleep(20000);
m_delay = new TimeSpan(0,0,300); //set a break-point here
base.OnStart(args);
try
{
m_thread = new System.Threading.Thread(Execute);
m_thread.Start();
_log.WriteToLog("Thread Started", LogLevel.Level0);
}
catch (Exception ex)
{ _log.WriteToLog(ex.Message, LogLevel.Level0); }
}
and once you start this service program in Windows Service, then you have to quickly attach you source code to the service program. In visual studio, it's menu "Debug" -> "Attach to Process...". then you can set break-point in your source code anywhere to check what's going wrong.
Do I need to wrap my code with try...catch statements if I use ELMAH?
I have the following code:
namespace ElmahTestApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
try
{
DateTime date = DateTime.Parse("asdasdasd");
}
catch (Exception ex)
{
}
return View();
}
}
}
The view shows up (as expected) however the exception does not get logged. Any suggestions? THanks in advance!
If you want your code to handle exceptions gracefully (eg, fallback to something else), you still need catch blocks.
Look at ErrorSignal. In your case, you'd do something like
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
I want to be able to track completed downloads served by my glassfish server. I couldn't find a 100% correct solution using servlet life cycle listeners.
Does anyone have a better idea?
Put a try-catch on IOException while serving the file download. If it's thrown, then serving the file download has failed.
E.g. in a custom file servlet:
try {
response.getOutputStream().write(...);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}
Or in a servlet filter which is mapped on the appropriate URL pattern matching file downloads:
try {
chain.doFilter(request, response);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}