CXF/ JAX-RS : Return Custom response from interceptor

前端 未结 2 432
忘了有多久
忘了有多久 2021-01-02 07:21

We need to return custom error code and error message when exception occurs during REST invocation. We have created a exception mapper provider, it works well for the except

2条回答
  •  旧巷少年郎
    2021-01-02 08:22

    I found a way to send a custom response from the interceptor but still can't figure out a way to call my CustomExceptionHandler from the interceptor

    Code:

    public void handleMessage(Message message) {
    
            MetadataMap metadataMap = (MetadataMap) message.get("jaxrs.template.parameters");
    
            if(null != metadataMap) {
                List list = metadataMap.get("phoneNumber");
                if(null != list) {
                    String phoneNumber = list.get(0);
                    boolean result = validatePhoneNumber(phoneNumber);
                    if(!result){
    // Create a response object and set it in the message. 
    // calling getExchange() will not call your service
                        Response response = Response
                    .status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString()))
                    .build();
            message.getExchange().put(Response.class, response);
    // That's it
                    }
                } else {
                    Response response = Response
                    .status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString()))
                    .build();
            message.getExchange().put(Response.class, response);
                }
            } else {
                Response response = Response
                    .status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString()))
                    .build();
            message.getExchange().put(Response.class, response);
            }
        }
    

提交回复
热议问题