为了最小的影响,我建议:ErrorActionResponse
作为StudentDTO
setter 和 getter 方法的私有成员。在服务中,当出现异常时,在's 成员中实例化ErrorActionResponse
并设置相同。StudentDTO
因此,客户必须首先检查是否getErrorActionResponse()
返回null
。如果是,则进行正常处理,否则,处理异常情况。
班级学生DTO:
public class StudentDTO {
...
private ErrorActionResponse errorActionResponse;
...
public ErrorActionResponse getErrorActionResponse() {
return errorActionResponse;
}
public void setErrorActionResponse( ErrorActionResponse errorActionResponse ) {
this.errorActionResponse = errorActionResponse;
}
}
服务:
@Override
public StudentDTO getStudent(@WebParam(name = "name") String studentName) {
StudentDTO student = new StudentDTO();
try {
student = studentService.findStudentByName(studentName);
}
catch (Exception e) {
student.setErrorActionResponse( new ErrorActionResponse("student couldn't find by name") );
}
finally {
return student;
}
}
客户代码:
if( student.getErrorActionResponse() == null ) {
// do normal processing
}
else {
// handle exception case
}
在上述情况下,DTO 具有ErrorActionResponse
与其基本状态无关的成员。所以,为了更简洁的方法,我建议你考虑Adapter pattern。