REST service: The proper way of returning exception

后端 未结 3 1148
太阳男子
太阳男子 2021-02-05 20:23

I use Jersey API for my REST service. My question is: Is there a more elegant way of returning exceptions in a JSON form? Is it better to concern myself with creating a json obj

3条回答
  •  失恋的感觉
    2021-02-05 21:03

    You can wrap your error into a class, say I have an ErrorData class which has status, message and stacktrace. Everytime an exception occurs, I throw a GeneralAppException with the errordata object.

    public class GeneralAppException  extends WebApplicationException {
     public GeneralAppException(ErrorData er) {
    
                super(Response.status(er.getStatusCode()).
                entity(er).type(MediaType.APPLICATION_JSON).build());
              }
    }
    

    I have another class which has all the known errors, eg.

    public static final ErrorData NODATAFOUND = new ErrorData(Response.Status.NOT_FOUND.getStatusCode(),"No data was found for given query");
    
    public static final ErrorData CODEERROR = new ErrorData(502,"CodeError");
    

    Your catch can look like

    catch (ExceptionREST e) {
            throw new GeneralAppException(ErrorData.NODATAFOUND);
        } 
    

    Reference used : https://jersey.java.net/documentation/latest/representations.html#d0e6665

提交回复
热议问题