从单个方法中根据条件抛出两个不同的自定义异常。创建自定义异常时,传递两件事,一件事是错误消息,另一件事是字符串形式的错误代码。但我无法根据错误代码获取错误。调用 processErrorCodes() 方法时出现错误。谁能帮我解决这个问题。
// BackgroundException is a custom EXCEPTION
public class BackgroundException extends Exception {
private static final long serialVersionUID = 4664456874499611218L;
private String errorCode="Unknown_Exception";
public BackgroundException(String message, String errorCode){
super(message);
this.errorCode=errorCode;
}
public String getErrorCode(){
return this.errorCode;
}
}
// Similarly I have InvalidException custom exception
public class MyExceptionTest {
public void methodTest(){
String policyId =null;
String policyNotification = null;
String policyStatus = null;
try {
if(policyNotification !=null) {
if(policyStatus!=null) {
if(policyId!=null) {
}
else{
throw new InvalidException("Policy ID Is Null","POLICY_ID");
}
}else{
throw new BackgroundException("Policy Status Is Null","POLICY_STATUS");
}
}
else{
throw new BackgroundException("Policy Notification Is Null","POLICY_NOTIFICATION");
}
} catch (BackgroundException | InvalidException e ) {
// TODO Auto-generated catch block
try {
processErrorCodes(e);
} catch (MyExcep e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.getMessage();
}
}
private static void processErrorCodes(Exception e) throws BackgroundException,InvalidException {
switch(e.getErrorCode()){
case "POLICY_NOTIFICATION":
System.out.println(e.getMessage());
throw e;
case "POLICY_ID":
System.out.println(e.getMessage());
throw e;
case "POLICY_STATUS":
System.out.println(e.getMessage());
throw e;
default:
System.out.println("Unknown exception occured, lets log it for further debugging."+e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
MyExceptionTest mt = new MyExceptionTest();
mt.methodTest();
}
}
I just want to handle those exceptions based on the error code.
最佳答案
您需要一个通用的父类(super class)来处理所有自定义异常,例如 MessageCodeException
,延伸Exception
并接受这个父类(super class)类型作为 processErrorCodes
内的参数方法
public abstract class MessageCodeException extends Exception {
public abstract String getCode();
// you can have a same abstract method for message
}
public class BackgroundException extends MessageCodeException {
// ...
}
public class InvalidException extends MessageCodeException {
// ...
}
//and now the process method will look like
private static void processErrorCodes(Exception e) throws ... {
// ...
}
很明显,对于当前的实现,您无法访问 code
字段,因为Exception
类接口(interface)不提供类似的东西
顺便说一句,创建异常驱动的业务验证逻辑似乎是一个非常糟糕的主意。创建某种 ValidationResult
不是更好吗?包含错误/警告/成功列表的对象并在最后处理此类验证结果? Exception
的目的存在并不是为了控制应用程序流程,而是为了强制用户为紧急情况提供一些支持(或者用 RuntimeException
处理某种意外情况)
关于java - 抛出多个自定义异常时如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57297231/