Home > Mobile >  Create and Return a custom Http response code in Java Spring Boot
Create and Return a custom Http response code in Java Spring Boot

Time:12-07

I want to create a custom http status code and want to return it with the response for specific use cases. I can not use the status codes like OK, ACCEPTED etc.

@RequestMapping(value = "/status/test", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Test> testStatus(@RequestBody Test test)
    throws Exception {
    // the below code is for status code 200

    HttpStatus httpStatus = HttpStatus.OK;

    // the above declaration declares the httpStatus with code 200 but I want to create
    // a custom code like 234
    
    return new ResponseEntity<Test>(test,httpStatus);

}

CodePudding user response:

you could take a look at the link provided by Andrew S in the comment.

another option is encapsulate the response into a custom java bean via @RestControllerAdvice, this custom java bean looks like

public class ResultVO<T> implements Serializable{

    private int code;
    private String msg;
    private T data;

then you could set any custom code in it.

CodePudding user response:

You could write your custom exception like this:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class AccountNotFoundException extends RuntimeException {
    public AccountNotFoundException(Exception ex, int id) {
        super("Account with id="   id   " not found", ex);
    }
}

Then throw the exception wherever you want. With @ResponseStatus you can give your exception it's own return code

  • Related