我正在使用@RestController将API添加到现有的Spring Boot项目中。
我的Spring Boot经验是:这是我第一次使用它。
当我发出格式正确的请求时,RestController可以正常工作,但是如果请求不正确(这是我所期望的),则会引发错误。但是,我不知道如何为用户提供有意义的错误响应。
这是Controller类:
@RestController
public class SomeController {
@PostMapping(value = "/update")
@ResponseBody
public ResponseEntity update(@RequestBody Config config) {
//do stuff
return ResponseEntity.ok(//response);
}
}
这是Config类:
@Getter
@Setter
@AllArgsConstructor
@Builder
public class Config {
private String thing1;
private String thing2;
}
如果我运行该应用程序并命中localhost:8080/update
:
{
"thing1": "dog",
"thing2": "cat",
}
然后,一切都很好,我们可以做一些事情了。
但是,如果我打localhost:8080/update
:
{
"thing1": "dog",
"thing2": 123,
}
我有一个例外: .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type...
这是预料之中的,因为我提供了一个数字,thing2需要一个字符串。
我得到的答复是: <h1>sorry</h1>
我不确定这是Spring的默认值还是配置在应用程序中的某个位置(如果是默认值,则找不到)。
我想将其更改为有意义的内容,例如:“您为thing2提供了错误的值”。
但是由于代码永远不会到达//做一些事情,所以我不确定该如何处理?
我试图用以下方法制作一个异常类:
@ControllerAdvice
@ExceptionHandler(HttpMessageNotReadableException.class)
但是我从IDE中收到“无法解析符号HttpMessageNotReadableException”。我什至不确定创建异常类是否是处理它的正确方法?
编辑:在本教程(https://www.toptal.com/java/spring-boot-rest-api-error-handling)中,Spring默认消息如下所示:
{
"timestamp": 1500597044204,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Unrecognized token 'three': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'aaa': was expecting ('true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@cba7ebc; line: 4, column: 17]",
"path": "/birds"
}
但是我就明白了<h1>sorry</h1>
。我实际上想要的更像上面的东西。
这应该可以工作,但是Spring不能在HTTP请求可以正确反序列化之前处理错误。您可以在反序列化之后使用DTO类的字段上的注释(例如@ NotNull,@ NotEmpty,@ Positive等)在请求数据上编写规则。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class ErrorController {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleException(HttpMessageNotReadableException exception, HttpServletRequest request) {
return new ResponseEntity("You gave an incorrect value for ....", HttpStatus.BAD_REQUEST);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句