简体   繁体   中英

How can I convert an error handling method into a Lambda function

Is there a way this method could be modified into a lambda function?

public static <T> void checkResponse(Response<T> response, String errorMessage, Map<String,String> values) throws IOException {
    if (!response.isSuccessful()) {
        String message = StringSubstitutor.replace(errorMessage, values);
        logger.error(message);
        throw new RuntimeException(message, null);
    }
}

First, define an interface with the appropriate parameters, then you can use a lambda to implement it.

@FunctionalInterface
interface ResponseHandler<T> {
   void handleResponse(Response<T> response, String errorMessage, Map<String,String> values);
}
// ...
ResponseHandler handler = (response, errorMessage, values) -> {
    if (!response.isSuccessful()) {
        String message = StringSubstitutor.replace(errorMessage, values);
        logger.error(message);
        throw new RuntimeException(message, null);
    }
};
// Call it:
handler.handleResponse(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM