[英]How to respond with an HTTP 400 error in a Spring MVC @ResponseBody method returning String
[英]How to respond with HTTP status code in a Spring MVC @RestController @ResponseBody class returning an object?
我正在尝试使用@RestController
,它使@PathVariable
返回JSON格式的特定对象,以及正确的状态代码。 到目前为止,代码的方式是,它将以JSON格式返回对象,因为默认情况下它使用的是Spring库中内置的Spring 4。
但是我不知道怎么做它所以它会给用户一个消息,说我们想要一个api变量,然后是JSON数据,然后是错误代码(或者成功代码取决于是否一切顺利)。 示例输出将是:
请输入api值作为参数(注意如果需要,这也可以是JSON)
{“id”:2,“api”:“3000105000”...}(注意这将是JSON响应对象)
状态代码400(或正确的状态代码)
带参数的url看起来像这样
http://localhost:8080/gotech/api/v1/api/3000105000
我到目前为止的代码:
@RestController
@RequestMapping(value = "/api/v1")
public class ClientFetchWellDataController {
@Autowired
private OngardWellService ongardWellService;
@RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET)
@ResponseBody
public OngardWell fetchWellData(@PathVariable String apiValue){
try{
OngardWell ongardWell = new OngardWell();
ongardWell = ongardWellService.fetchOneByApi(apiValue);
return ongardWell;
}catch(Exception ex){
String errorMessage;
errorMessage = ex + " <== error";
return null;
}
}
}
@RestController
不适合这个。 如果需要返回不同类型的响应,请使用ResponseEntity<?>
,您可以在其中显式设置状态代码。
ResponseEntity
的body
将以与任何@ResponseBody
注释方法的返回值相同的方式处理。
@RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET)
public ResponseEntity<?> fetchWellData(@PathVariable String apiValue){
try{
OngardWell ongardWell = new OngardWell();
ongardWell = ongardWellService.fetchOneByApi(apiValue);
return new ResponseEntity<>(ongardWell, HttpStatus.OK);
}catch(Exception ex){
String errorMessage;
errorMessage = ex + " <== error";
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}
请注意,在@RestController
注释类中的@RequestMapping
方法上不需要@ResponseBody
。
惯用的方法是使用异常处理程序而不是在常规请求处理方法中捕获异常。 异常类型确定响应代码。 (403表示安全错误,500表示意外平台异常,无论您喜欢什么)
@ExceptionHandler(MyApplicationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleAppException(MyApplicationException ex) {
return ex.getMessage();
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAppException(Exception ex) {
return ex.getMessage();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.