Search code examples
xpagesxpages-ssjs

Set response code in rest control


I can't figure out how to set response code in my REST control element.

enter image description here

Here is the code of REST control.

    <xe:restService id="restProfile" pathInfo="profile">
    <xe:this.service>
        <xe:customRestService
            doGet="#{javascript:REST_PROFILE.doGet()}"
            contentType="application/json"
            doPost="#{javascript:REST_PROFILE.doPost(reqVar)}"
            requestContentType="application/json" requestVar="reqVar">
        </xe:customRestService>
    </xe:this.service>
</xe:restService>

The requirement is to return code 404 in some cases and I can't find out how to do it.

Does anybody know how to do it using SSJS?

Version of Domino is 9.0.1


Solution

  • You can't return a status 404 with doGet and doPost. The response property status is managed by the customRestService. The SSJS code can return JSON data only.
    You might define your own JSON content like

    {
        "status": "error",
        "error-message": "something not found"
    } 
    

    though and handle errors this way.

    As an alternative you can use customRestService's serviceBean.

            <xe:customRestService
                contentType="application/json"
                requestContentType="application/json"
                serviceBean="de.leonso.demo.RestService">
            </xe:customRestService>
    

    and set return code with response.setStatus(status) there:

    public class RestService extends CustomServiceBean {
        @Override
        public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
            try {
                HttpServletRequest request = engine.getHttpRequest();
                HttpServletResponse response = engine.getHttpResponse();
                response.setHeader("Content-Type", "application/json; charset=UTF-8");
                response.setContentType("application/json");
                response.setHeader("Cache-Control", "no-cache");
                response.setCharacterEncoding("utf-8");
    
                String method = request.getMethod();
                int status = 200;
                if (method.equals("GET")) {
                    status = ...
                } else {
                    ...
                }
                response.setStatus(status);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }