简体   繁体   中英

how to return a response body when header is missing in spring REST api

I am passing a header to a spring REST api like:

@RequestHeader(value="test-header")

header is mandatory here for the API, so I do not want to keep it optional. when no header is passed, any call to the API returns a standard 400 error indicating that request is syntantically wrong and then it does not enter the REST API. But, I want to construct a proper ResponseBody and return a json for this error. I am not sure about the best way to do this. I thought about using spring interceptor and check if this header was passed or not, but then I am not sure if I can create a responsebody from here. Atleast I could not figure out how to do so.

will interceptor approach work for this? If yes, how? If not, then what are the options? Can someone please help on this?

Update:

This is how the REST API is:

public void methodA(@RequestHeader(value="test-header") String header, @RequestBody User user, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
...
...

} 

When the header is present, it will enter the REST API and continue with the logic. But, if the header is not present, it does not enter the API and simply returns a standard 400 error.

The interceptor that I wrote is like:

public class XXXInterceptor extends HandlerInterceptorAdapter { 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
...
...
...

return true;
}

}

STEP1: Use spring validator annotation like @valid to validate your request.

STEP 2: Write your custom validator class. which will be responsible to check the header and see if it has value or it has the expected value.

STEP 3: If the request is not correct validator throws your custom exception.

STEP 4: write your exception handler class. In the class define what response must me returned if the exception in STEP 3 is caught.

For more information on Exception Handling in Spring .

In our current projet we do use a java interceptor to authenticate the request but nothing beyound that.

Another approach would be using Spring Interceptors ( HandlerInterceptorAdapter ), as you mentioned in your question, with @ControllerAdvice and return your JSON in an @ExceptionHandler method.

Take a look at the following post: http://www.journaldev.com/2651/spring-mvc-exception-handling-exceptionhandler-controlleradvice-handlerexceptionresolver-json-response-example

Write a method with the annotation @ExceptionHandler and use ServletRequestBindingException.class as this exception is thrown in case of miss. You can return any type of object from this method.

For example

@ExceptionHandler(ServletRequestBindingException.class)
public ResponseEntity<ResponseObject> handleHeaderError(){

    ResponseObject responseObject=new ResponseObject();
    responseObject.setStatus(Constants.ResponseStatus.FAILURE.getStatus());
    responseObject.setMessage(header_missing_message);

    ResponseEntity<ResponseObject> responseEntity=new ResponseEntity<ResponseObject>(responseObject, HttpStatus.BAD_REQUEST);
    return responseEntity;
}

This is coming late but then, a very straightforward way to deal with this type of issue is to use a Controller Advice class which allows you to handle exceptions across the whole application in one global handling component.

The exception throw by spring is the MissingRequestHeaderException which you can then provide a custom handler in your controller advice class.

@Slf4j
@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(MissingRequestHeaderException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public ErrorResponse handleMissingRequestHeaderException(MissingRequestHeaderException ex) {
        log.error(ex.getMessage(), ex);
        return new ErrorResponse("Missing request header: " + ex.getHeaderName());
    }

}
public class ErrorResponse implements Serializable {
    
    private String message;

    public ErrorResponse(String message) {
        this.message = message;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM