java 休息服务抛出异常:最好的处理方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15907202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rest service throws exception : Best way to handle
提问by AnujKu
I have a rest service which will throw an exception and I want to know what will be the best way to handle this.
我有一个会抛出异常的休息服务,我想知道处理这个问题的最佳方法是什么。
So I have a rest service which can throw a userdefined exception and I am catching that inside the catch block and throwing that exception again ! and using rest framework to catch that. Similarly for non-user defined exceptions. I thought this will be good as I have number of rest services and all userdefinedexception code handling will be at a same place.
所以我有一个休息服务,它可以抛出一个用户定义的异常,我在 catch 块中捕获它并再次抛出该异常!并使用休息框架来捕捉它。对于非用户定义的异常也是如此。我认为这会很好,因为我有许多休息服务,并且所有用户定义的异常代码处理都将在同一个地方。
I would like to know is this the proper way of handling exception in rest service ?
我想知道这是在休息服务中处理异常的正确方法吗?
I am using jersey.
我正在使用球衣。
// 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
回答by hamilton.lima
Just raising error 500 at the server don't give much details on the error, one way to gracefully handle errors, is to wrap the response data in a structure with status and data, if the status is error, show the correct message.
只是在服务器上引发错误 500 并没有提供有关错误的太多详细信息,一种优雅地处理错误的方法是将响应数据包装在具有状态和数据的结构中,如果状态为错误,则显示正确的消息。
something like this in json format :
像这样的 json 格式:
{
"status": "error",
"data": {
"message": "detailed error message"
}
}
回答by Bruno Grieder
Handling exceptions in a REST service is not much different from handling exceptions in any other piece of code.
在 REST 服务中处理异常与在任何其他代码段中处理异常没有太大区别。
The only "convention" is to throw back an HTTP 400 if the exception is triggered by the client sending incorrect data and a 500 when your service is failing unexpectedly.
唯一的“约定”是如果客户端发送不正确的数据触发异常,则返回 HTTP 400,当您的服务意外失败时返回 500。