简体   繁体   English

在 JAVA 的自定义异常中返回 arrayList 作为消息

[英]Return an arrayList as message in custom exception in JAVA

I need to output a List<String> when an exception is thrown.抛出异常时,我需要 output 一个List<String> I want the program to stop its execution once the exception is thrown.一旦抛出异常,我希望程序停止执行。 To make things clear, my code has these two functions:为了清楚起见,我的代码具有以下两个功能:

       List<String> exceptions = new ArrayList<>();
    
        public Boolean validation(Obj obj){
           if(condition1){ exceptions.add("exception1");}
           if(condition2){ exceptions.add("exception2");}
              .
              .
              .
           if(exceptions.size() > 0) return false;
           else return true;
        }
    
        public Obj getValidResponse(Obj obj){
           if(validation(obj)){ return obj;}
           else{ throw new CustomException(exceptions);}  //on this line, the program should return the List<String> of all the exceptions stored. 
        }

Whenever I throw the exception, the list is printed following the technical exception message which I do not want.每当我抛出异常时,都会在我不想要的技术异常消息之后打印列表。 Also, I cannot figure out a way to return using a getMessage() function implemented in my customException, in the throw statement as it gives a Expected throwable type error.此外,我无法在 throw 语句中找到使用在我的 customException 中实现的getMessage() function 返回的方法,因为它给出了Expected throwable type错误。

My Custom exception class looks like:我的自定义异常 class 看起来像:

public class CustomException extends RuntimeException{
    public CustomException(List<String> s) {
        super(String.valueOf(s));
    }
}

I am pretty new to this, any kind of help would be really appreciated.我对此很陌生,任何形式的帮助都将不胜感激。 :) :)

You can do this by sub classing from RuntimeException (use a proper name and fields for the exception to make is self descriptive):您可以通过从 RuntimeException 进行子类化来做到这一点(使用正确的名称和字段以使异常具有自我描述性):

public class CustomException extends RuntimeException {

    private List<String> myStrings;

    public CustomException(List<String> s) {
        this.myString = s;
    }

    public List<String> getMyStrings() {
        return myStrings;
    }

    public String getMessage() {
        return String.join(",", myStrings);
    }
}

Java can only throw Throwables , no other objects. Java 只能抛出Throwables ,不能抛出其他对象。 This is different from other programming languages.这与其他编程语言不同。 And the getMessage method which is used for a string representation is always returning a String .用于字符串表示的getMessage方法总是返回一个String When you need a different behavior returning the real list you have to use you own interceptor / fault barrier reading the list of strings directly and apply a proper handling.当您需要返回真实列表的不同行为时,您必须使用自己的拦截器/故障屏障直接读取字符串列表并应用适当的处理。

Can you be more precise when you need the list of string as List<String> .当您需要将字符串列表作为List<String>时,您能否更精确。 It seems you are using some handler code not only interested in the string message of the exception.看来您正在使用一些处理程序代码,不仅对异常的字符串消息感兴趣。 In your code it seems that you are trying to return an Obj .在您的代码中,您似乎正在尝试返回Obj Is your idea here to return an error list instead if it fails?如果失败,您的想法是返回错误列表吗? This does not work that way.这不是那样工作的。 If you throw something then this will raise an exception and nothing is returned.如果你抛出一些东西,那么这将引发一个异常并且什么都不返回。 This is a different program flow.这是一个不同的程序流程。 If you want to return the list of errors you could also create a special如果您想返回错误列表,您还可以创建一个特殊的

public class StatusResult {

    private boolean error;
    
    private Obj sucessObj;
   
    private List<String> errorMsgs;

// add constructor and getters here ...
}

But this kind of success / error handling is not Java like.但是这种成功/错误处理不是Java之类的。

Well here is one solution for such custom exception class:那么这是针对此类自定义异常 class 的一种解决方案:

public class CustomException extends Exception{

    private final List<String> errors;

    public CustomException(List<String> errors) {
        this.errors = errors;
    }

    @Override
    public String getMessage() {

        String msg = errors.stream()
                .collect(Collectors.joining(", ", "[", "]"));

        return msg;
    }

}

You can use it as follows:您可以按如下方式使用它:

public static void main(String[] args) {

    try {
        errorFunc();
    } catch (CustomException exception) {
        System.out.println(exception.getMessage());
    }
}

public static void errorFunc() throws  CustomException {

    List<String> errors = new ArrayList<>();
    errors.add("error#1");
    errors.add("error#2");
    errors.add("error#3");

    throw new CustomException(errors);
}

Output: Output:

[error#1, error#2, error#3]

But please note that this is not good practice in general.但请注意,这通常不是好的做法。 An exception should represent one error and not multiple ones.一个异常应该代表一个错误而不是多个错误。 Normally you would create a base class, which represents a special "category" of your exceptions.通常你会创建一个基础 class,它代表你的异常的一个特殊“类别”。 Then specific errors can have their own exception that is derived from that base exception.然后,特定错误可以有自己的异常,该异常源自该基本异常。 One example is the FileNotFoundExcpetion ( https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html ), which is derived from IOException (which in turn is derived from the Exception class). One example is the FileNotFoundExcpetion ( https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html ), which is derived from IOException (which in turn is derived from the Exception class).

Throwing a string of multiple errors might indicate that your function is doing more than one thing (and these things might go wrong).抛出一串多个错误可能表明您的 function 正在做不止一件事(这些事情可能 go 错误)。

import java.util.ArrayList;
import java.util.List;
public class CustomException extends Exception{
    private List<String> exceptions;
    public CustomException(List<String> exp) {
        this.exceptions = exp;
    }   
    public List<String> getExceptions(){
        return exceptions;
    }
    public static void main(String[] args) {
    
        try {
            boolean result = getValidResponse();
        }catch(CustomException e) {
            List<String> msgs = e.getExceptions();
            for(String ss:msgs) {
                System.out.println(ss);
            }
        }
    }   
    static List<String> exps = new ArrayList<String>(); 
    public static boolean validation(boolean error){
        boolean result = false;
        if(error) {         
            exps.add("Error msg 1");
            exps.add("Error msg 2");            
        }else{
            result =  true;
        }        
        return result;
    }   
    public static boolean getValidResponse() throws CustomException{
        boolean r = false;
        validation(true);
        if(exps.size()>0) {
            throw new CustomException(exps);
        }
        return r;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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