REST service: The proper way of returning exception

后端 未结 3 1114
太阳男子
太阳男子 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:02

    I believe it is quite popular that people use http response status code to handle the error. E.g. 404 status is not found 5xx is server internal error e.t.c. You can easily set the error code by using the Response object. Instead of returning a map, return a Response object.

    @Path("/admin")public class AdminService {
    
    @Context
    HttpServletRequest request;
    
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public Response createCompany(Company company){
    
        Map map = new HashMap<>();
        try{
            AdminFacade adminFacade = (AdminFacade)Utility.getFacade(request);
            Company commpany=adminFacade.createCompany(company);//this entity annotated by XmlRootElement
            Response response=Response.ok().entity(company).build();
        } catch (ExceptionREST e) {
            response=Response.status(404).build();
        } return response;
    }}
    

    To make the Restful api more robust, some will return an OK response to prevent "smart redirect" from the server and output some weird html. you can refer here for a list of http status code and what it mean. For Java EE Response class, you can refer the official javadoc

提交回复
热议问题