[英]Spring Boot Rest Controller how to return different HTTP status codes?
I am using Spring Boot for a simple REST API and would like to return a correct HTTP statuscode if something fails.我正在使用 Spring 启动一个简单的 REST API 并想返回一个正确的 Z293C9EA246FF985DC86F678 错误代码。
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
@ResponseBody
@ResponseStatus( HttpStatus.OK )
public RestModel create(@RequestBody String data) {
// code ommitted..
// how do i return a correct status code if something fails?
}
Being new to Spring and Spring Boot, the basic question is how do i return different status codes when something is ok or fails?作为 Spring 和 Spring 启动的新手,基本问题是当事情正常或失败时如何返回不同的状态码?
There are several options you can use.您可以使用多个选项。 Quite good way is to use exceptions and class for handling called
@ControllerAdvice
:很好的方法是使用异常和类进行处理,称为
@ControllerAdvice
:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
Also you can pass HttpServletResponse
to controller method and just set response code:您也可以将
HttpServletResponse
传递给控制器方法并设置响应代码:
public RestModel create(@RequestBody String data, HttpServletResponse response) {
// response committed...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
Please refer to the this great blog post for details: Exception Handling in Spring MVC有关详细信息,请参阅这篇很棒的博文: Spring MVC 中的异常处理
In Spring MVC using @ResponseBody
annotation is redundant - it's already included in @RestController
annotation.在 Spring MVC 中使用
@ResponseBody
注释是多余的 - 它已经包含在@RestController
注释中。
One of the way to do this is you can use ResponseEntity as a return object.一种方法是您可以使用 ResponseEntity 作为返回对象。
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
if(everything_fine) {
return new ResponseEntity<>(RestModel, HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
A nice way is to use Spring's ResponseStatusException一个不错的方法是使用 Spring 的ResponseStatusException
Rather than returning a ResponseEntity
or similar you simply throw the ResponseStatusException
from the controller with an HttpStatus
and cause, for example:而不是返回
ResponseEntity
或类似的,您只需从控制器中抛出ResponseStatusException
带有HttpStatus
和原因,例如:
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cause description here");
This results in a response to the client containing the HTTP status:这会导致对包含 HTTP 状态的客户端的响应:
{
"timestamp": "2020-07-09T04:43:04.695+0000",
"status": 400,
"error": "Bad Request",
"message": "Cause description here",
"path": "/test-api/v1/search"
}
Note : HttpStatus
provides many different status codes for your convenience.注意:为方便起见,
HttpStatus
提供了许多不同的状态代码。
In case you want to return a custom defined status code, you can use the ResponseEntity as here:如果您想返回自定义定义的状态代码,您可以使用 ResponseEntity 如下:
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
int customHttpStatusValue = 499;
Foo foo = bar();
return ResponseEntity.status(customHttpStatusValue).body(foo);
}
The CustomHttpStatusValue could be any integer within or outside of standard HTTP Status Codes. CustomHttpStatusValue 可以是标准 HTTP 状态代码之内或之外的任何整数。
Try this code:试试这个代码:
@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
int numberHTTPDesired = 400;
ErrorBean responseBean = new ErrorBean();
responseBean.setError("ERROR");
responseBean.setMensaje("Error in validation!");
return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}
There are different ways to return status code, 1 : RestController class should extends BaseRest class, in BaseRest class we can handle exception and return expected error codes.返回状态码有多种方式,1:RestController类应该继承BaseRest类,在BaseRest类中我们可以处理异常并返回预期的错误码。 for example :
例如 :
@RestController
@RequestMapping
class RestController extends BaseRest{
}
@ControllerAdvice
public class BaseRest {
@ExceptionHandler({Exception.class,...})
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorModel genericError(HttpServletRequest request,
HttpServletResponse response, Exception exception) {
ErrorModel error = new ErrorModel();
resource.addError("error code", exception.getLocalizedMessage());
return error;
}
I think the easiest way is to make return type of your method as我认为最简单的方法是将您的方法的返回类型设置为
ResponseEntity<WHATEVER YOU WANT TO RETURN>
and for sending any status code, just add return statement as并且要发送任何状态代码,只需将 return 语句添加为
return ResponseEntity.status(HTTP STATUS).build();
For example, if you want to return a list of books,例如,如果您想返回书籍列表,
public ResponseEntity<List<books>> getBooks(){
List<books> list = this.bookService.getAllBooks();
if(list.size() <= 0)
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
else
return ResponseEntity.of(Optional.of(list));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.