我有一个休息服务,它会抛出异常,我想知道处理这个问题的最佳方法是什么。
所以我有一个休息服务,它可以抛出用户定义的异常,我在 catch 块内捕获该异常并再次抛出该异常!并使用休息框架来捕捉这一点。对于非用户定义的异常也是如此。我认为这会很好,因为我有许多休息服务,并且所有用户定义的异常代码处理都将在同一个地方。
我想知道这是处理休息服务异常的正确方法吗?
我正在使用球衣。
// 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
仅在服务器上引发错误 500,不会提供有关错误的详细信息,优雅处理错误的一种方法是将响应数据包装在包含状态和数据的结构中,如果状态为错误,则显示正确的消息。
json 格式是这样的:
{
"status": "error",
"data": {
"message": "detailed error message"
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)