How can i cover Junit test for an Exception's root cause? - exception

I have the following block of code for which I want to increase code coverage:
try{
discountReferenceCustomerRepository.saveAllAndFlush(discountReferenceCustomersNew);
} catch (DataIntegrityViolationException ex) {
if(ex.getRootCause() != null && ex.getRootCause().toString().contains("Duplicate entry")){
LOGGER.error("{}::{}:: Attempt to persist duplicate data : [{}]", CdfConstants.CDF_CORE_SERVICE_NAME, DUPLICATE_DATA_ERROR, ex);
throw new SystemException("Attempt to persist one or more duplicate records ",ERROR_MSG_DUPLICATE_DATA);
} else {
throw ex;
}
}
return new ResponseStatusVO("Added new ORG to existing RCD for given EA");
}
I am unable to cover the "ex.getRootCause()" section, because in my Junit test, all i do is:-
when(repository.saveAllAndFlush(any())).thenThrow(new DataIntegrityViolationException("test"));
The root exception is SQLIntegrityConstraintViolationException with the message that says "Duplicate Entry". This error is then propagated by DataIntegrityViolationException which i can catch in my code.
Obviously, i am unable to do something like "ex.setRootCause" in my Junit coz there ain't such api defined in the library.
What can i do to increase coverage ?

Related

EntityFramework exception: How can i see the real query

Sometimes i have an EntityFramework exception where calling SaveChanges.
I see this kind of message: "An error occurred while updating the entries. See the inner exception for details."
I have logged the stack trace, the inner exception and stuff but there is no clear explanation of the problem. I would like to see the real query (it is a mysql database), with the parameters. Do you know how i can see or log the real query ?
Thanks
You can use DbEntityValidationException handler which will let you know what was wrong precisely.
try{
//Your code here
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullMessageError = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, "Exact Message " + fullMessageError);
}
catch (Exception ex)
{
//General Exception here
}
You can set log property of dbContext.Database and log the actual queries generated by EF.
using (var context = new MyDBContext())
{
context.Database.Log = Console.Write; // This is where you setup where to log queries
// Your code here...
}
There is a detailed documentation on MSDN https://msdn.microsoft.com/en-us/data/dn469464.aspx

How not to fail Hadoop MapReduce job for one database insert failure?

I'm writing a MapReduce job to mine webserver logs. The input is from text files, output goes to a MySQL database. Problem is, if one record fails to insert, for whatever reason, like data exceeding column size, the whole job fails and nothing gets written to the database. Is there a way so that the good records are still persisted? I guess one way would be to validate the data but that couples the client with the database schema too much for my taste.
I'm not posting the code because this is not particularly a code issue.
Edit:
Reducer:
protected void reduce(SkippableLogRecord rec,
Iterable<NullWritable> values, Context context) {
String path = rec.getPath().toString();
path = path.substring(0, min(path.length(), 100));
try {
context.write(new DBRecord(rec), NullWritable.get());
LOGGER.info("Wrote record {}.", path);
} catch (IOException | InterruptedException e) {
LOGGER.error("There was a problem when writing out {}.", path, e);
}
}
Log:
15/03/01 14:35:06 WARN mapred.LocalJobRunner: job_local279539641_0001
java.lang.Exception: java.io.IOException: Data truncation: Data too long for column 'filename' at row 1
at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:529)
Caused by: java.io.IOException: Data truncation: Data too long for column 'filename' at row 1
at org.apache.hadoop.mapreduce.lib.db.DBOutputFormat$DBRecordWriter.close(DBOutputFormat.java:103)
at org.apache.hadoop.mapred.ReduceTask$NewTrackingRecordWriter.close(ReduceTask.java:550)
at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:629)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:389)
at org.apache.hadoop.mapred.LocalJobRunner$Job$ReduceTaskRunnable.run(LocalJobRunner.java:319)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
15/03/01 14:35:06 INFO mapred.LocalJobRunner: reduce > reduce
15/03/01 14:35:07 INFO mapreduce.Job: Job job_local279539641_0001 failed with state FAILED due to: NA
Answering my own question and looking at this SO post, I see that the database write in done in a batch, and on SQLException, the transaction is rolled back. So that explains my problem. I guess I'll just have to make the DB columns big enough, or validate first. I can also create a custom DBOutputFormat/DBRecordWriter but unless I insert one record at a time, there'll always be a risk of one bad record causing the whole batch to rollback.
public void close(TaskAttemptContext context) throws IOException {
try {
LOG.warn("Executing statement:" + statement);
statement.executeBatch();
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
}
catch (SQLException ex) {
LOG.warn(StringUtils.stringifyException(ex));
}
throw new IOException(e.getMessage());
} finally {
try {
statement.close();
connection.close();
}
catch (SQLException ex) {
throw new IOException(ex.getMessage());
}
}
}

How to know exception occurred within grails transaction?

I have a service method which does some operation inside a transaction.
public User method1() {
// some code...
Vehicle.withTransaction { status ->
// some collection loop
// some other delete
vehicle.delete(failOnError:true)
}
if (checkSomething outside transaction) {
return throw some user defined exception
}
return user
}
If there is a runtime exception we dont have to catch that exception and the transaction will be rolled back automatically. But how to determine that transaction rolled back due to some exception and I want to throw some user friendly error message. delete() call also wont return anything.
If I add try/catch block inside the transaction by catching the Exception (super class) it is not getting into that exception block. But i was expecting it to go into that block and throw user friendly exception.
EDIT 1: Is it a good idea to add try/catch arround withTransaction
Any idea how to solver this?? Thanks in advance.
If I understand you question correctly, you want to know how to catch an exception, determine what the exception is, and return a message to the user. There are a few ways to do this. I will show you how I do it.
Before I get to the code there are a few things I might suggest. First, you don't need to explicitly declare the transaction in a service (I'm using v2.2.5). Services are transactional by default (not a big deal).
Second, the transaction will automatically roll back if any exception occurs while executing the service method.
Third, I would recommend removing failOnError:true from save() (I don't think it works on delete()... I may be wrong?). I find it is easier to run validate() or save() in the service then return the model instance to the controller where the objects errors can be used in a flash message.
The following is a sample of how I like to handle exceptions and saves using a service method and try/catch in the controller:
class FooService {
def saveFoo(Foo fooInstance) {
return fooInstance.save()
}
def anotherSaveFoo(Foo fooInstance) {
if(fooInstance.validate()){
fooInstance.save()
}else{
do something else or
throw new CustomException()
}
return fooInstance
}
}
class FooController {
def save = {
def newFoo = new Foo(params)
try{
returnedFoo = fooService.saveFoo(newFoo)
}catch(CustomException | Exception e){
flash.warning = [message(code: 'foo.validation.error.message',
args: [org.apache.commons.lang.exception.ExceptionUtils.getRootCauseMessage(e)],
default: "The foo changes did not pass validation.<br/>{0}")]
redirect('to where ever you need to go')
return
}
if(returnedFoo.hasErrors()){
def fooErrors = returnedFoo.errors.getAllErrors()
flash.warning = [message(code: 'foo.validation.error.message',
args: [fooErrors],
default: "The foo changes did not pass validation.<br/>${fooErrors}")]
redirect('to where ever you need to go')
return
}else {
flash.success = [message(code: 'foo.saved.successfully.message',
default: "The foo was saved successfully")]
redirect('to where ever you need to go')
}
}
}
Hope this helps, or gets some other input from more experienced Grails developers.
Here are a few other ways I've found to get exception info to pass along to your user:
request.exception.cause
request.exception.cause.message
response.status
A few links to other relevant questions that may help:
Exception handling in Grails controllers
Exception handling in Grails controllers with ExceptionMapper in Grails 2.2.4 best practice
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html

Spring MVC Exceptions

I have the following code in the Controller class and for some reason although i have exception handling implemented as well as a try.....catch block i am still unable to capture my exceptions.
I am just executing a test, in the DAO class i change the sql string that inserts into the database to leave out a column just so the DAO will fail. The DAO class fails and the error is written to the logs however even thou the officerManager.RegisterOfficer(officer) was not successful the code goes on to return the model.addAttribute("results","Record Was Saved").
This is not accurate and i would like for the controller to throw an error. Under is the code.
Controller
#RequestMapping(value="officer_registration.htm", method=RequestMethod.POST)
public ModelAndView handleRequest(#Valid #ModelAttribute Officers officer,BindingResult result,ModelMap m,Model model,HttpServletRequest request,HttpServletResponse response)throws Exception{
try{
if(result.hasErrors()){
model.addAttribute("division", myDivision);
model.addAttribute("position", myPosition);
model.addAttribute("gender", myGender);
return new ModelAndView("officer_registration");
}else{
//check the request if its an update or an insert
String user_request = request.getParameter("user_request");
logger.info("The Users Request Was " + user_request);
if (user_request.equals("Save")){
officerManager.RegisterOfficer(officer);
model.addAttribute("results","Record Was Saved");
}else{
officerManager.UpdateOfficer(officer);
model.addAttribute("results","Record Was Updated");
}
model.addAttribute("division", myDivision);
model.addAttribute("position", myPosition);
model.addAttribute("gender", myGender);
return new ModelAndView("officer_registration");
}
}catch(Exception e ){
model.addAttribute("division", myDivision);
model.addAttribute("position", myPosition);
model.addAttribute("gender", myGender);
model.addAttribute("results","Error: Unable to Save Record!");
return new ModelAndView("officer_registration");
}
}
DAO
public void saveOfficer(Officers officer) {
logger.info("In saveOfficer");
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try{
int count = getJdbcTemplate().update("INSERT INTO crimetrack.tblofficers (userName,password, fName, lName, oName, divisionNo, positionId, emailAdd, startDate, endDate, genderId,phoneNo, dob,badgeNo) "+
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
, new Object[]{officer.getUserName(),StringSecurity.EncryptString(officer.getPassword()),officer.getfName(),
officer.getlName(),officer.getoName(),officer.getDivisionNo(),officer.getPositionId(),
officer.getEmailAdd(),officer.getStartDate(),officer.getEndDate(),officer.getGenderId(),
officer.getPhoneNo(),officer.getDob(),officer.getBadgeNo()});
logger.info(count +" Rows affected in tblOfficers");
}catch(Exception e){
logger.error("Could not save officer ", e);
}
}
You're not allowing the error to bubble up back to the controller.
You're handling the exception within the DAO, in which case the method exits normally, and no exception is caught within the Controller.
Either don't surround the DAO with a try catch and let the exception bubble back to the controller (recommended), or catch and rethrow the exception (if you follow this route, throw as a RuntimeException, either create your own, or rethrow as a RuntimeException, that way you won't have to catch all the way through the call stack.)
Also, it's generally frowned upon to catch generic exception as it is tougher to nail down exactly what caused it unless you look within the logs. Knowing which exceptions to handle ahead of time is usually better practice.

Is there any way to customize Active Directories exception/error message?

I am using Active Directory as a data store for the users of my website. I have Active Directory throwing the following exception in case password does not meet any password policy constraint..
-->The password supplied is invalid.
Passwords must conform to the password
strength requirements configured for
the default provider.
Can I customize this error messages/notifications in any way to be them more specific??
What I want is that - If 'password history' is the constraint that is violated then the error message should say so (ex. New password should be different than the last 10 used passwords..)
Any help is appreciated.
you can catch that and throw you own message
try {
// your error will probably appear here
if (MembershipService.ValidateUser(usr, pwd))
{
...
}
}
catch(Exception ex)
{
// Let's see if we have Inner Exceptions to deal
if(ex.InnerException != null)
while(ex.InnerException != null)
ex = ex.InnerException;
// Now, let's check our exception
if(ex.Message.StartsWith("The password supplied is invalid. Passwords must conform to the password strength requirements configured for the default provider."))
{
throw new Exception("My custom message goes here");
}
// Let's throw the original one
throw ex;
}
Is this what you are trying to accomplish?
Well you should see the exact type of Exception that is thrown, and setup a specific catch for this exception.
If you see this link, http://msdn.microsoft.com/en-us/library/0yd65esw.aspx, you will see that you can catch multiple specific Exceptions.
You could then return whatever msg you want to the user.