简体   繁体   中英

What are the best practice of making code error stable?

I need make some code super stable and make sure all exceptions thrown within a block don't stop the code execution.

For now i have the following solution:

iterated.map(it -> {
   try {
      handleElement(it);
   } catch (Exception e) {
      handleError(e);
   }
});

But from the other side i feel like there should be more elegant way to do it. Please help me to find it.

There is nothing wrong with you code and probably I would keep as is but if you like you can have a function that handles another function and catches the exceptions:

public class ExceptionCatcher<T, R> implements Function<T, R> {

    public final Function<T, R> function;

    public final Function<Exception, R> exceptionHandler;

    public ExceptionCatcher(Function<T, R> function, Function<Exception, R> exceptionHandler) {
        this.function = function;
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public R apply(T o) {
        try {
            return function.apply(o);
        }catch (Exception e){
            return exceptionHandler.apply(e);
        }

    }
};

and your code will look like:

ExceptionCatcher ex = new ExceptionCatcher(this::handleElement, this::handleError);
iterated.map(ex);

This is just an example; probably instead of a simple Consumer you want a BiFunction and map to a default value based on the exception and on the failing onject. Or return null and filter null after this. It depends a lot on what you want to achieve

Well that's indeed how to call exceptions, but it's more important how to deal with these occurrences. An Exception should be thrown when the app experiences something which it could not expect. Just catching all exceptions will

  • Not make your code more stable, it just doesn't throw exceptions higher up
  • Leave errors as-is, and they will still be thrown (you probably want this)
  • Remove exceptions which you might want to have logged

Keep in mind what is a REAL exception for your app. Here are some examples:

  • You have a connection to a backend, which is unstable. You knew this, and made the app possible to reconnect and/or postpone the actions, or whatever in order for the app that this backend is in fact unstable:
    • This is NO exception, just log a message if needed.
  • The client misentered some information
    • NO exception, this happens all the time, the app should cope with that
  • After some code update you have a problem even setting up the connection
    • EXCEPTION: log it and fix the problem!

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