我有一个休息服务,它将抛出一个异常,我想知道什么是最好的方法来处理这个 .
所以我有一个休息服务,可以抛出一个用户定义的异常,我在catch块中捕获并再次抛出异常!并使用rest框架来捕获它 . 同样适用于非用户定义的异常 . 我认为这将是好的,因为我有许多休息服务,所有userdefinedexception代码处理将在同一个地方 .
我想知道这是在休息服务中处理异常的正确方法吗?
我正在使用运动衫 .
// rest service
@POST
public void doSomething() {
try {
// ... some piece of code that can throw user defined exception as well as runtime exception
} catch(UserDefinedException e) {
throws new UserDefinedException(e);
} catch(Exception e) {
throws new ServiceException(e);
}
// Now I have a @Provider to catch this thrown exception
@Provider
public class UserDefinedExceptionHandler implements
ExceptionMapper {
public Response toResponse(UserDefinedException exception) {
ClientResponse clientResponse = new ClientResponse();
ResponseStatus status = new ResponseStatus();
clientResponse = handleUserDefinedException(exception, status, clientResponse);
return Response.ok(clientResponse).build();
}
// similarly for the ServiceException
2 回答
只是在服务器上引发错误500并没有提供有关错误的详细信息,一种优雅地处理错误的方法是将响应数据包装在具有状态和数据的结构中,如果状态是错误,则显示正确的消息 .
像json格式这样的东西:
处理REST服务中的异常与处理任何其他代码中的异常没有太大区别 .
唯一的“约定”是,如果客户端发送错误数据触发异常,则返回HTTP 400,当服务意外失败时触发500 .