[英]Create and Return a custom Http response code in Java Spring Boot
我想创建一个自定义 http 状态代码,并希望将其与特定用例的响应一起返回。 我不能使用OK
、 ACCEPTED
等状态码。
@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);
}
您可以查看 Andrew S 在评论中提供的链接。
另一种选择是通过@RestControllerAdvice
将响应封装到自定义 java bean 中,这个自定义 java bean 看起来像
public class ResultVO<T> implements Serializable{
private int code;
private String msg;
private T data;
然后您可以在其中设置任何自定义代码。
您可以像这样编写自定义异常:
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);
}
}
然后在任何你想要的地方抛出异常。 使用 @ResponseStatus 你可以给你的异常它自己的返回码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.