2012-05-28 179 views
1

返回错误我有一个这样的类:在Java Web服务

@Override 
public StudentDTO getStudent(@WebParam(name = "name") String studentName) { 
    StudentDTO student = new StudentDTO(); 
    try { 
     student = studentService.findStudentByName(studentName); 
    } catch (Exception e) { 
     return new ErrorActionResponse("student couldn't find by name"); 
    } 
    return student; 
} 

像往常一样,这并不因为返回类型的工作是StudentDTO我尝试返回另一个类型的类:ErrorActionResponse。 ErrorActionResponse是一个具有关于错误的详细信息的错误类。

如何设计可处理错误情况的Web服务体系结构? (在我的REST架构我写错误信息到响应,并发送错误客户端)

回答

1

如果你想返回一个Collection(如我在前面的回答中的评论中所述),我建议你用两个键创建一个Map。如果没有例外,则第一个键值对将分别包含“students”字符串和StudentDTO集合。而第二个键值对将分别包含“异常”字符串和空值。如果有例外,第一个键值对将分别包含“students”字符串和空值。并且,第二个键值对将分别为“例外”字符串和一个ErrorActionResponse对象。例如:

也不例外情况:

Map<String, List> result = new HashMap<String, List>(); 
result.put("students", COLLECTION_OF_STUDENTS); 
result.put("exception", null); 

也不例外情况:

Map<String, List> result = new HashMap<String, List>(); 
result.put("students", null); 
result.put("exception", ErrorActionResponse_OBJECT); 

希望这有助于...

1

对于影响最小,我建议: 使ErrorActionResponse作为StudentDTO与setter和getter方法的私有成员。在服务中,当出现异常时,例化ErrorActionResponse并在StudentDTO的成员中设置相同。因此,客户必须首先检查getErrorActionResponse()是否返回null。如果是这样,则执行正常处理,处理异常情况。

CLASS StudentDTO:

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

+0

如果我尝试返回学生的名单,我将需要设置所有学生的errorActionResponse在列表 – kamaci

+0

我同意。我的第一个建议是针对您的OP要求 - 返回学生而不是列表的方法(您现在要说明)。 – San