Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @RequestBody and forwarding to another endpoint throws exception Stream closed

Tags:

java

spring

My Java spring REST API controller looks like this:

public void signup(@RequestBody RequestBody requestBody) throws IOException, ServletException {

I get this exception:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Stream closed; nested exception is java.io.IOException: Stream closed

This happens because I want to cast the request body to RequestBody class (which opens the request input stream and finishes it), and also forward/redirect it to another endpoint.

The actual controller is:

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public void signup(@RequestBody CustomUserDetails user, HttpServletRequest request, HttpServletResponse response) {

        String userName = user.getUsername();
        logger.debug("User signup attempt with username: " + userName);

        try{
            if(customUserDetailsService.exists(userName))
            {
                logger.debug("Duplicate username " + userName);
userName + " already exists");
                String newUrl = "login";
                RequestDispatcher view = request.getRequestDispatcher(newUrl);
                view.forward(request, response);
            } else {
                customUserDetailsService.save(user);
                authenticateUserAndSetSession(user, response);
            }
        } catch(Exception ex) {

        }
    }

How should I handle this ?

like image 323
Arian Avatar asked May 09 '17 06:05

Arian


1 Answers

You can forward to login page in a ExceptionHandler,like this:

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public void signup(@RequestBody CustomUserDetails user, HttpServletResponse response) {

    String userName = user.getUsername();
    logger.debug("User signup attempt with username: " + userName);

    //try{
    if (customUserDetailsService.exists(userName)) {
        logger.debug("Duplicate username " + userName);
        throw new SignupException(userName + " already exists");
    } else {
        customUserDetailsService.save(user);
        authenticateUserAndSetSession(user, response);
    }
    /*} catch(Exception ex) {

    }*/
}

define a ExceptionHandler in the same Controller:

@ExceptionHandler(SignupException.class)
public String duplicateName() {
    return "login";
}

and the SignupException could be like this:

public class SignupException extends RuntimeException {
    public SignupException(String message) {
        super(message);
    }

    public SignupException() {
    }
}
like image 197
rayen Avatar answered Oct 27 '22 14:10

rayen