Spring MVC Rest Service Controller with Error Handling done right?

后端 未结 5 760
一向
一向 2020-12-08 15:06

I was wondering how to correctly implement a Spring Controller which is supposed to serve as a REST Service. Especially I want to try and make the interface as RESTful as po

5条回答
  •  失恋的感觉
    2020-12-08 15:34

    Firstly, I think you should always return a object when returning JSON. Even when something goes horribly wrong.

    When something goes wrong you simply set response.setStatus() and return a resource describing the error.

    public class ErrorResource implements Resource {
        private final int status;
        private final String message;
    
        public ErrorResource(int s, String m) {
            status = s;
            message = m;
        }
    
        public int getStatus() {
            return status;
        }
    
        public String getMessage() {
            return message;
        }
    }
    

    The resource gets serialized and the outcome would be

    {"status":500, "message":"Yay!"}
    

    Using a Map will work but I would like to advise you to write some resource classes which define the object to be returned. They would be easier to maintain. Maps don't offer any structure while structure is a very important part when creating a REST service.

    I don't think you should return a resource with the raw exception message embedded. It can potentially leak information you don't want anyone to see.

提交回复
热议问题