Narendra Pandey
Narendra Pandey

Reputation: 436

How to catch and modify data over exception occurred during Stream usage

I am currently working over CSV exports. I am fetching header from properties file with below code -

String[] csvHeader = exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s ->messageSource.getMessage("report."+s, null, locale)).toArray(String[]::new);

The above code works well. But i need to find a way to handle exception and also fetch data from another file, if it is not found in above file. I am expecting to use somewhat below code -

try{
    exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
    map(s ->messageSource.getMessage("report."+s, null, locale)).toArray(String[]::new);
    }catch(NoSuchMessageException e){
    // code to work over lacking properties 
    }

I want to catch the 's' element in catch block (or in other good way). So that i can fetch it from another file and also add its return to current csvHeader.

Upvotes: 1

Views: 107

Answers (1)

Level_Up
Level_Up

Reputation: 824

One way is to make for each element a try catch block like:

 exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s -> {
            String result;//Put the class to which you map

            try{
                result = messageSource.getMessage("report."+s, null, locale);
              }catch(NoSuchMessageException e){
              // code to work over lacking properties here you have access to s
              }
              return result;
         }
   ).toArray(String[]::new);

Another solution will be to check for specific problems and then there is no need to catch exceptions. For example if s is null and then you want to get the data from another place:

 exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s -> {
            String result;//Put the class to which you map
            if(null == s)// Some condition that you want to check.
            {
                //get info from another place
                //result = ....
            }
            else
            {
                result = messageSource.getMessage("report."+s, null, locale);
            }
            return result;
         }
   ).toArray(String[]::new);

Upvotes: 3

Related Questions