问题描述
我有一个休息服务,会抛出一个异常,我想知道最好的办法是什么。
I have a rest service which will throw an exception and I want to know what will be the best way to handle this.
所以我有一个休息服务可以抛出一个用户定义的异常,我在catch块中捕获它并再次抛出异常!并使用rest框架来捕获它。类似地,对于非用户定义的异常。我认为这会很好,因为我有多少休息服务,所有userdefinedexception代码处理将在同一个地方。
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.
我想知道这是正确的方法在休息服务中处理异常?
I would like to know is this the proper way of handling exception in rest service ?
我正在使用球衣。
// 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没有提供有关错误的详细信息,优雅地处理错误的一种方法是将响应数据包装在具有状态和数据的结构中,如果状态是错误,则显示正确的消息。
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.
json格式的这样的东西:
something like this in json format :
{
"status": "error",
"data": {
"message": "detailed error message"
}
}
这篇关于休息服务抛出异常:最好的处理方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!