简体   繁体   English

休息服务引发异常:处理的最佳方法

[英]Rest service throws exception : Best way to handle

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 ! 因此,我有一个rest服务,它可以引发用户定义的异常,而我正在catch块中捕获该异常并再次引发该异常! and using rest framework to catch that. 并使用rest框架来捕捉这一点。 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中处理异常的正确方法吗?

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

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"
    }
}

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM